ES6+ Features
What I Learned Today
Modern JavaScript (ES6 and beyond) introduced features that made the language more powerful, readable, and developer-friendly. Hereβs a summary:
- Template Literals
What It Does: Enables string interpolation and multi-line strings.
Example:
let year = 2024;
console.log(`This is year ${year}`);
- Benefits: Easier to read and manage strings compared to traditional concatenation.
- Arrow Functions
What It Does: Provides a shorter syntax for writing functions.
Example:
let add = (a, b) => console.log(`${a} + ${b} = ${a + b}`);
add(4, 5); // Output: 4 + 5 = 9
- Benefits: Simplifies code, especially for inline functions.
- Default Parameters
What It Does: Assigns default values to function parameters if no argument is passed.
Example:
function callMe(name = "Damilare") {
console.log(`My name is ${name}`);
}
callMe(); // Output: My name is Damilare
callMe("Ayoola"); // Output: My name is Ayoola
- Benefits: Prevents errors from missing parameters.
- Destructuring
- What It Does: Extracts values from arrays or objects and assigns them to variables. Examples:
//Array Destructuring:
const [a, b] = [2, 3];
console.log(a, b); // Output: 2 3
//Object Destructuring:
const { age, year } = { age: 32, year: "Year 5" };
console.log(age, year); // Output: 32 Year 5
- Benefits: Makes code cleaner and reduces repetitive access to object properties or array elements.
- Spread and Rest Operators (...)
-
Spread
: Expands elements of an array or object into individual elements.
const arr1 = [0, 1, 2];
const arr2 = [...arr1, 3, 4, 5];
console.log(arr2); // Output: [0, 1, 2, 3, 4, 5]
-
Rest
: Collects remaining elements into a single array or object.
const collectRest = (first, ...rest) => {
console.log(`First number is ${first}`);
console.log(`The rest of the numbers: ${rest}`);
};
collectRest(1, 2, 3, 4);
// Output:
// First number is 1
// The rest of the numbers: [2, 3, 4]
- for...of Loop
What It Does: Simplifies looping over iterable objects (like arrays).
Example:
let arr = [1, 2, 3, 4, 5];
for (let num of arr) {
console.log(num);
}
// Output:
// 1
// 2
// 3
// 4
// 5
- Benefits: Avoids the need to manually access array indices and improves readability.
Top comments (0)