Modern ES6+ Features and Modules
About 398 wordsAbout 5 min
2025-08-05
This page covers the modern syntax that makes JavaScript more powerful and expressive, focusing on data manipulation and code organization.
Destructuring In-Depth
Destructuring is a powerful tool for extracting data from arrays and objects.
- Aliasing: Rename properties as you extract them.
const { id: userID } = user;
- Default Values: Provide a fallback value if a property is
undefined
.const { role = 'guest' } = user;
- Nested Destructuring: Extract properties from nested objects in one go.
const { profile: { name } } = user;
- Function Parameters: Destructure object parameters directly in the function signature for cleaner, self-documenting code.
// Destructuring with default values in a function parameter
function createUser({ name, role = 'user' }) {
console.log(`Creating ${role}: ${name}`);
}
createUser({ name: "Alex" });
Spread (`...`) vs. Rest (`...`)
Though they use the same syntax, their function is opposite.
Spread (
...
): Expands an iterable into its individual elements.- Use Cases: Creating shallow copies of arrays/objects, merging arrays/objects, passing array elements as arguments to a function.
const arr1 = [1, 2]; const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4] const obj1 = { a: 1 }; const obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 } -->
Rest (
...
): Collects remaining elements into a single array or object.- Use Cases: Gathering all remaining arguments in a function signature, collecting remaining elements during array destructuring.
function sum(...numbers) { /* numbers is an array */ } const [first, ...rest] = [1, 2, 3, 4]; // first is 1, rest is [2, 3, 4]
ES Modules (ESM) In-Depth
ESM is the standard for organizing JavaScript code.
- Static Nature:
import
andexport
are static. They are processed at compile time, not runtime. This allows for powerful tooling like tree-shaking (removing unused code). - Named vs. Default Exports: A module can have multiple
named
exports but only onedefault
export. Default exports are useful for the "main" export of a file (like a class or primary function), while named exports are good for utility functions and constants. - Dynamic
import()
: While ESM is static, you can dynamically load modules at runtime using theimport()
function, which returns a Promise. This is essential for code-splitting and lazy-loading modules on demand.button.addEventListener('click', async () => { // Load the module only when the button is clicked const module = await import('./utils.js'); module.doSomething(); });
Changelog
8/8/25, 4:17 AM
View All Changelog
2aa48
-web-deploy(Auto): Update base URL for web-pages branchon
Copyright
Copyright Ownership:WARREN Y.F. LONG
License under:Attribution-NonCommercial-NoDerivatives 4.0 International (CC-BY-NC-ND-4.0)