JavaScript Design Patterns: Deliver fast and efficient production-grade JavaScript applications at scale
()
About this ebook
Unlock the potential of JavaScript design patterns, the foundation for development teams seeking structured and reusable solutions to common software development challenges in this guide to improving code maintainability, scalability, and performance. Discover how these patterns equip businesses with cleaner and more maintainable code, promote team collaboration, reduce errors, and save time and costs.
This book provides a comprehensive view of design patterns in modern (ES6+) JavaScript with real-world examples of their deployment in professional settings. You’ll start by learning how to use creational, structural, and behavioral design patterns in idiomatic JavaScript, and then shift focus to the architecture and UI patterns. Here, you’ll learn how to apply patterns for libraries such as React and extend them further to general web frontend and micro frontend approaches. The last section of the book introduces and illustrates sets of performance and security patterns, including messaging and events, asset and JavaScript loading strategies, and asynchronous programming performance patterns.
Throughout the book, examples featuring React and Next.js, in addition to JavaScript and Web API examples, will help you choose and implement proven design patterns across diverse web ecosystems, transforming the way you approach development.
Related to JavaScript Design Patterns
Related ebooks
Building Real-World Web Applications with Vue.js 3: Build a portfolio of Vue.js and TypeScript web applications to advance your career in web development Rating: 0 out of 5 stars0 ratingsFull-Stack Web Development with TypeScript 5: Craft modern full-stack projects with Bun, PostgreSQL, Svelte, TypeScript, and OpenAI Rating: 0 out of 5 stars0 ratingsAngular for Enterprise Applications: Build scalable Angular apps using the minimalist Router-first architecture Rating: 0 out of 5 stars0 ratingsReal-World Next.js: Build scalable, high-performance, and modern web applications using Next.js, the React framework for production Rating: 0 out of 5 stars0 ratingsSvelteKit Up and Running: Leverage the power of a next-generation web framework to build high-performance web apps with ease Rating: 0 out of 5 stars0 ratingsBuilding Your Own JavaScript Framework: Architect extensible and reusable framework systems Rating: 0 out of 5 stars0 ratingsAngular Design Patterns and Best Practices: Create scalable and adaptable applications that grow to meet evolving user needs Rating: 0 out of 5 stars0 ratingsReact Anti-Patterns: Build efficient and maintainable React applications with test-driven development and refactoring Rating: 0 out of 5 stars0 ratingsJavaScript from Frontend to Backend: Learn full stack JavaScript development using the MEVN stack with quick and easy steps Rating: 0 out of 5 stars0 ratingsASP.NET 3.5 Application Architecture and Design Rating: 0 out of 5 stars0 ratingsClean Android Architecture: Take a layered approach to writing clean, testable, and decoupled Android applications Rating: 0 out of 5 stars0 ratingsDeploying Node.js Rating: 5 out of 5 stars5/5Nuxt 3 Projects: Build scalable applications with Nuxt 3 using TypeScript, Pinia, and Composition API Rating: 0 out of 5 stars0 ratingsJavaScript Domain-Driven Design Rating: 3 out of 5 stars3/5Ultimate Node.js for Cross-Platform App Development Rating: 0 out of 5 stars0 ratingsHands-On Microservices with Django: Build cloud-native and reactive applications with Python using Django 5 Rating: 0 out of 5 stars0 ratingsFrontend Software Development and Best Practices: A Concise Guide Rating: 5 out of 5 stars5/5Architecting ASP.NET Core Applications: An atypical design patterns guide for .NET 8, C# 12, and beyond Rating: 0 out of 5 stars0 ratingsEffective Angular: Develop applications of any size by effectively using Angular with Nx, RxJS, NgRx, and Cypress Rating: 0 out of 5 stars0 ratingsReact Application Architecture for Production: Learn best practices and expert tips to deliver enterprise-ready React web apps Rating: 0 out of 5 stars0 ratingsUltimate Tailwind CSS Handbook: Build sleek and modern websites with immersive UIs using Tailwind CSS Rating: 0 out of 5 stars0 ratingsBeginning React: Simplify your frontend development workflow and enhance the user experience of your applications with React Rating: 0 out of 5 stars0 ratingsResponsive Web Design with HTML5 and CSS: Build future-proof responsive websites using the latest HTML5 and CSS techniques Rating: 0 out of 5 stars0 ratingsUltimate Web Authentication Handbook Rating: 0 out of 5 stars0 ratings
Programming For You
Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsLearn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Raspberry Pi Electronics Projects for the Evil Genius Rating: 3 out of 5 stars3/5C Programming For Beginners: The Simple Guide to Learning C Programming Language Fast! Rating: 5 out of 5 stars5/5HTML in 30 Pages Rating: 5 out of 5 stars5/5Problem Solving in C and Python: Programming Exercises and Solutions, Part 1 Rating: 5 out of 5 stars5/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5Nostalgia and Videogame Music: A Primer of Case Studies, Theories, and Analyses for the Player-Academic Rating: 0 out of 5 stars0 ratingsMicrosoft Azure For Dummies Rating: 0 out of 5 stars0 ratingsHTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Narrative Design for Indies: Getting Started Rating: 4 out of 5 stars4/5
Reviews for JavaScript Design Patterns
0 ratings0 reviews
Book preview
JavaScript Design Patterns - Hugo Di Francesco
JavaScript Design Patterns
Copyright © 2024 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Rohit Rajkumar
Publishing Product Manager: Kushal Dave
Senior Content Development Editor: Feza Shaikh
Technical Editor: Simran Udasi
Copy Editor: Safis Editing
Project Coordinator: Aishwarya Mohan
Indexer: Subalakshmi Govindhan
Production Designer: Jyoti Kadam
Marketing Coordinators: Nivedita Pandey and Anamika Singh
First published: March 2024
Production reference: 1150224
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK
ISBN 978-1-80461-227-9
www.packtpub.com
To my wife, Amalia, for being my first supporter in all my endeavors. To my daughter, Zoë, for making me want to show that the impossible sometimes is.
– Hugo Di Francesco
Contributors
About the author
Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds an MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier, and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes, while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
I want to thank all the people who have supported me in my life and writing journey, particularly my wife Amalia, and my family.
About the reviewers
Dr. Murugavel, a distinguished and versatile educator in the realms of computer science engineering and information technology. With over 13 years of enriching experience at renowned universities and an additional 8+ years dedicated to the dynamic field of data analytics, Dr. Murugavel stands as a beacon of expertise at the intersection of academia and technology.
His journey is marked by successive achievements, particularly in handling core subjects and programming languages, with a keen emphasis on practical knowledge. As a mentor and guide for major projects, Dr. Murugavel actively engages in groundbreaking research within his specialized field. His commitment to bridging theory and application has made him a valuable resource for students and researchers alike.
His technical proficiency extends across a spectrum of disciplines. He is well-versed in full stack web development, SQL, data analytics, Python, and BI tools, showcasing theoretical knowledge and a hands-on understanding of these technologies. His extensive portfolio includes the development of numerous applications using JSP, ASP, and ASP.NET, reflecting his prowess in both frontend and backend development.
In the realm of databases, he demonstrates versatility across MS-SQL Server, MySQL, MongoDB, Django, MS Access, Oracle, and FoxPro. His proficiency in various Integrated Development Environments (IDEs) and tools such as Anaconda, Visual Studio, GitHub, JBuilder, JCreator, MATLAB, Sublime 3, and Adobe Dreamweaver further solidifies his standing in the technological landscape.
In the realm of data science and Business Intelligence (BI) tools, his skills are extensive, encompassing PowerBI, DAX, VBA Macros for Excel, SSAS, and SSIS. His ability to harness these tools illuminates the path to insightful data analysis and visualization.
Shubham Thakur, a dynamic senior software engineer (A3 grade) at EPAM, specializes in technologies such as JavaScript, Angular, Next.js, Node, MySQL, MongoDB, AWS Cloud, and IoT. His expertise in these domains has significantly contributed to his project successes. He expresses deep gratitude to Priya for her unwavering love and to his brother, Yash, for his constant support. Shubham also acknowledges the profound impact of his mentors, Avnish Aggarwal, Yogesh Dhandekar, and Amit Jain, whose guidance has been instrumental in shaping his professional journey. Their mentorship has not only honed his technical skills but also enriched his approach to complex problem-solving in the tech industry.
Table of Contents
Preface
Part 1: Design Patterns
1
Working with Creational Design Patterns
What are creational design patterns?
Implementing the prototype pattern in JavaScript
Implementation
A use case
The singleton pattern with eager and lazy initialization in JavaScript
Implementation
Use cases
Improvements with the class singleton
pattern
A singleton without class fields using ES module behavior
The factory pattern in JavaScript
Implementation
Use cases
Improvements with modern JavaScript
Summary
2
Implementing Structural Design Patterns
Technical requirements
What are structural design patterns?
Implementing the Proxy pattern with Proxy and Reflect
A redaction proxy implementation
Use cases
Improving the proxy pattern in JavaScript with the Proxy and Reflect global objects
Decorator in JavaScript
Implementation
Use cases
Improvements/limitations
Flyweight in JavaScript
Implementation
Use cases
Improvements/limitations
Adapter in JavaScript
Use cases
Improvements/limitations
Summary
3
Leveraging Behavioral Design Patterns
Technical requirements
What are behavioral design patterns?
The observer pattern in JavaScript
Implementation
Use cases of the observer pattern
Limitations and improvements
State and strategy in JavaScript and a simplified approach
Implementation
Use cases of the state and strategy patterns
Limitations and improvements
Visitor in JavaScript
Implementation
Use cases of the visitor pattern
Summary
Part 2: Architecture and UI Patterns
4
Exploring Reactive View Library Patterns
Technical requirements
What are reactive view library patterns?
The render prop pattern
Use cases
Implementation/example
Limitations
The higher-order component pattern
Implementation/example
Use cases
Limitations
The hooks pattern
An implementation/example
Use cases
Limitations
The provider pattern
Use case – the prop drilling problem
An implementation/example
Limitations
Summary
5
Rendering Strategies and Page Hydration
Technical requirements
Client and server rendering with React
Client-side rendering in React
Server rendering in React
Trade-offs between client and server rendering
Static rendering with Next.js
Automatic static generation
Static generation with a third-party data source
Static generation with dynamic paths
Page hydration strategies
Common React rehydration issues
React streaming server-side rendering
Summary
6
Micro Frontends, Zones, and Islands Architectures
Technical requirements
An overview of micro frontends
Key benefits
Classic
micro frontend patterns
Other concerns in a micro frontend world
Composing applications with Next.js zones
Root app
Adding a /search app
Adding /checkout app
The benefits/supporting team scaling
The drawbacks of Next.js zones
Scaling performance-sensitive pages with the islands
architecture
Islands setup with is-land
Product island
Cart island
A related products island
Scaling with a team – bundling islands
Drawbacks
Summary
Part 3: Performance and Security Patterns
7
Asynchronous Programming Performance Patterns
Technical requirements
Controlling sequential asynchronous operations with async/await and Promises
Parallel asynchronous operation patterns
Asynchronous cancellation and timeouts with AbortController
Throttling, debouncing, and batching asynchronous operations
Summary
8
Event-Driven Programming Patterns
Technical requirements
Optimizing event listeners through event delegation
Patterns for secure frame/native WebView bridge messaging
Event listener performance antipatterns
Summary
9
Maximizing Performance – Lazy Loading and Code Splitting
Technical requirements
Dynamic imports and code splitting with Vite
Route-based code splitting and bundling
Loading JavaScript on element visibility and interaction
Summary
10
Asset Loading Strategies and Executing Code off the Main Thread
Technical requirements
Asset loading optimization – async, defer, preconnect, preload, and prefetch
Using Next.js Script’s strategy option to optimize asset loading
Loading and running scripts in a worker thread
Summary
Index
Other Books You May Enjoy
Preface
Welcome! JavaScript design patterns are techniques that allow us to write more robust, scalable, and extensible applications in JavaScript. JavaScript is the main programming language available in web browsers and is one of the most popular programming languages with support beyond browsers.
Design patterns are solutions to common problems that can be reused. The most-written-about design patterns come from the world of object-oriented programming.
JavaScript’s attributes as a lightweight, multi-paradigm, dynamic, single-threaded language give it different strengths and weaknesses to other mainstream programming languages. It’s common for software engineers to use JavaScript in addition to being well versed in a different programming language. JavaScript’s different gearing means that implementing design patterns verbatim can lead to non-idiomatic and under-performing JavaScript applications.
There are many resources on JavaScript and design patterns, but this book provides a cohesive and comprehensive view of design patterns in modern (ECMAScript 6+) JavaScript with real-world examples of how to deploy them in a professional setting. In addition to this complete library of patterns to apply to projects, this book also provides an overview of how to structure different parts of an application to deliver high performance at scale.
In this book, you will be provided with up-to-date guidance through the world of modern JavaScript patterns based on nine years of experience building and deploying JavaScript and React applications at scale at companies such as Elsevier, Canon, and Eurostar, delivering multiple system evolutions, performance projects, and a next-generation frontend application architecture.
Who this book is for
This book is for developers and software architects who want to leverage JavaScript and the web platform to increase productivity, software quality, and the performance of their applications.
Familiarity with software design patterns would be a plus but is not required.
The three main challenges faced by developers and architects who are the target audience of this content are as follows:
They are familiar with programming concepts but not how to effectively implement them in JavaScript
They want to structure JavaScript code and applications in a way that is maintainable and extensible
They want to deliver more performance to the users of their JavaScript applications
What this book covers
Chapter 1, Working with Creational Design Patterns, covers creational design patterns, which help to organize object creation. We’ll look at implementing the prototype, singleton, and factory patterns in JavaScript.
Chapter 2, Implementing Structural Design Patterns, looks at structural design patterns, which help to organize relationships between entities. We’ll implement the proxy, decorator, flyweight, and adapter patterns in JavaScript.
Chapter 3, Leveraging Behavioral Design Patterns, delves into behavioral design patterns, which help to organize communication between objects. We’ll learn about the observer, state, strategy, and visitor patterns in JavaScript.
Chapter 4, Exploring Reactive View Library Patterns, explores reactive view libraries, such as React, which have taken over the JavaScript application landscape. With these libraries come new patterns to explore, implement, and contrast.
Chapter 5, Rendering Strategies and Page Hydration, takes a look at optimizing page performance, which is a key concern nowadays. It’s a concern both for improving the on-page conversion of customers and search engine optimization, since search engines such as Google take core web vitals into account.
Chapter 6, Micro Frontends, Zones, and Islands Architectures, explores micro frontends. Akin to the microservices movement in the service tier, micro frontends are designed to split a large surface area into smaller chunks that can be worked on and delivered at higher velocity.
Chapter 7, Asynchronous Programming Performance Patterns, looks at how JavaScript’s single-threaded event-loop-based concurrency model is one of its greatest strengths but is often misunderstood or under-leveraged in performance-sensitive situations. Writing asynchronous-handling code in JavaScript in a performant and extensible manner is key to delivering a smooth user experience at scale.
Chapter 8, Event-Driven Programming Patterns, explores how event-driven programming in JavaScript is of paramount importance in security-sensitive applications as it is a way to pass information from and to different web contexts. Event-driven applications can often be optimized to enable better performance and scalability.
Chapter 9, Maximizing Performance – Lazy Loading and Code Splitting, deals with how, in order to maximize the performance of a JavaScript application, reducing the amount of unused JavaScript being loaded and interpreted is key. The techniques that can be brought to bear on this problem are called lazy loading and code splitting.
Chapter 10, Asset-Loading Strategies and Executing Code off the Main Thread, looks at how there are situations in the lifecycle of an application where loading more JavaScript or assets is inevitable. You will learn about asset-loading optimizations in the specific case of JavaScript, as well as other web resources, and finally how to execute JavaScript off the main browser thread.
To get the most out of this book
You will need to have prior experience with JavaScript and developing for the web. Some of the more advanced topics in the book will be of interest to developers with intermediate experience in building for the web with JavaScript.
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
Download the example code files
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/JavaScript-Design-Patterns. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Conventions used
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: In order to make the code easier to follow, we’ll switch on the lowercased version of tagName.
A block of code is set as follows:
// handle receiving messages from iframe -> parent
const allowedMessageOrigins = ['http://127.0.0.1:8000'];
window.addEventListener('message', (event) => {
if (!allowedMessageOrigins.includes(event.origin)) {
console.warn(
`Dropping message due to non-allowlisted origin ${event.origin}`,
event,
);
return;
}
// no change to the rest of the message handler
});
Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: When opening the select, things seem to work ok, we’re seeing the Fruit: prefix for all the options.
Tips or important notes
Appear like this.
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Share Your Thoughts
Once you’ve read JavaScript Design Patterns, we’d love to hear your thoughts! Please click here to go straight to the Amazon review pagefor this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Download a free PDF copy of this book
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?
Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read