Early praise for Simplifying JavaScript You should probably jot down each Tip from this book on Post-It notes and plaster them all over your desk area. These simple, practical bits of advice will have a profound effect on simplifying your JavaScript. ➤ Kyle Simpson Author of You Don’t Know JS and Open Web Evangelist Joe provides a clear, organized path to mastering key JavaScript concepts. This isn’t a boring textbook. It’s a playbook filled with practical, real-world approaches to writing modular, maintainable, and modern JavaScript. ➤ Cory House Pluralsight Author and International Speaker and Consultant, reactjsconsulting.com This book is great for experienced developers whose past experience with Java- Script has left a bad taste in their mouth. Modern JavaScript, when understood through this book, is sure to turn former critics into advocates. New developers will also benefit from thorough explanations that are in layman’s terms—not the overly technical jargon that typically acts as a barrier to entry with many technical books. ➤ Sara Heins International Speaker, Django Girls Kansas City Program Director, and Lead Web Developer, Big 6 Media This book is ideal for beginners as well as intermediate and beyond. ➤ Shreerang Patwardhan Author of Mastering jQuery Mobile, Senior Software Engineer, Macy’s Inc. I would definitely recommend this book to others on my team. I believe that most, if not all, of my team could benefit from reading this book. ➤ Nick McGinness Software Engineer, Direct Supply Simplifying JavaScript Writing Modern JavaScript with ES5, ES6, and Beyond Joe Morgan The Pragmatic Bookshelf Raleigh, North Carolina Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade- marks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. Our Pragmatic books, screencasts, and audio books can help you and your team create better software and have more fun. Visit us at https://pragprog.com. The team that produced this book includes: Publisher: Andy Hunt VP of Operations: Janet Furlow Managing Editor: Brian MacDonald Supervising Editor: Jacquelyn Carter Development Editor: Andrea Stewart Copy Editor: Nancy Rapoport Indexing: Potomac Indexing, LLC Layout: Gilson Graphics For sales, volume licensing, and support, please contact [email protected]. For international rights, please contact [email protected]. Copyright © 2018 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. ISBN-13: 978-1-68050-288-6 Encoded using the finest acid-free high-entropy binary digits. Book version: P1.0—April 2018 To Bob and Eric for giving me a foundation Contents Introduction . . . . . . . . . . . . . xi 1. Signal Intention with Variable Assignment . . . . . 1 Tip 1. Signal Unchanging Values with const 3 Tip 2. Reduce Scope Conflicts with let and const 6 Tip 3. Isolate Information with Block Scoped Variables 10 Tip 4. Convert Variables to Readable Strings with Template Literals 14 2. Manage Data Collections with Arrays . . . . . . 17 Tip 5. Create Flexible Collections with Arrays 19 Tip 6. Check Existence in an Array with Includes() 23 Tip 7. Mold Arrays with the Spread Operator 25 Tip 8. Avoid Push Mutations with the Spread Operator 30 Tip 9. Avoid Sort Confusion with the Spread Operator 34 3. Maximize Code Clarity with Special Collections . . . . 39 Tip 10. Use Objects for Static Key-Value Lookups 41 Tip 11. Create Objects Without Mutations Using Object.assign() 45 Tip 12. Update Information with Object Spread 50 Tip 13. Update Key-Value Data Clearly with Maps 54 Tip 14. Iterate Over Key-Value Data with Map and the Spread Operator 60 Tip 15. Create Maps Without Side Effects 66 Tip 16. Keep Unique Values with Set 69 4. Write Clear Conditionals . . . . . . . . . . 73 Tip 17. Shorten Conditionals with Falsy Values 75 Tip 18. Check Data Quickly with the Ternary Operator 79 Tip 19. Maximize Efficiency with Short Circuiting 82 Contents • viii 5. Simplify Loops . . . . . . . . . . . . 87 Tip 20. Simplify Looping with Arrow Functions 89 Tip 21. Write Shorter Loops with Array Methods 93 Tip 22. Create Arrays of a Similar Size with map() 98 Tip 23. Pull Out Subsets of Data with filter() and find() 102 Tip 24. Apply Consistent Actions with forEach() 107 Tip 25. Combine Methods with Chaining 110 Tip 26. Transform Array Data with reduce() 114 Tip 27. Reduce Loop Clutter with for...in and for...each 120 6. Clean Up Parameters and Return Statements . . . . 127 Tip 28. Create Default Parameters 129 Tip 29. Access Object Properties with Destructuring 133 Tip 30. Simplify Key-Value Assignment 140 Tip 31. Pass a Variable Number of Arguments with the Rest Operator 143 7. Build Flexible Functions . . . . . . . . . 149 Tip 32. Write Functions for Testability 151 Tip 33. Reduce Complexity with Arrow Functions 157 Tip 34. Maintain Single Responsibility Parameters with Partially Applied Functions 160 Tip 35. Combine Currying and Array Methods for Partial Application 165 Tip 36. Prevent Context Confusion with Arrow Functions 171 8. Keep Interfaces Clear with Classes . . . . . . . 175 Tip 37. Build Readable Classes 177 Tip 38. Share Methods with Inheritance 180 Tip 39. Extend Existing Prototypes with Class 184 Tip 40. Simplify Interfaces with get and set 187 Tip 41. Create Iterable Properties with Generators 192 Tip 42. Resolve Context Problems with Bind() 198 9. Access External Data . . . . . . . . . . 203 Tip 43. Retrieve Data Asynchronously with Promises 205 Tip 44. Create Clean Functions with Async/Await 211 Tip 45. Make Simple AJAX Calls with Fetch 214 Tip 46. Maintain State Over Time with LocalStorage 218 10. Gather Related Files with Component Architecture . . . 221 Tip 47. Isolate Functionality with Import and Export 223