ES6 Features
In the intro article, we have talked about origin of JS and its progression through ES versions. With the release of ES6 (ECMAScript 2015), JavaScript introduced a range of modern features that improved the language’s readability, functionality, and developer experience.
Template Literals
Section titled “Template Literals”Template literals provide an intuitive way to embed variables and expressions within strings. Instead of concatenating strings manually, you can use backticks ` ` combined with placeholders ${expression}
.
const name = "User";console.log(`Hello, ${name}!`); // Hello, User!
This feature is especially helpful when working with long strings, multi-line strings, or embedding dynamic content.
Destructuring Arrays and Objects
Section titled “Destructuring Arrays and Objects”Destructuring allows you to unpack values from arrays or properties from objects into distinct variables. This makes the process of assigning values more concise and readable.
Destructuring Arrays:
Section titled “Destructuring Arrays:”const fruits = ["apple", "banana", "cherry"];const [first, second, third] = fruits;console.log(first); // appleconsole.log(second); // banana
Destructuring Objects:
Section titled “Destructuring Objects:”const person = { name: "User", age: 30, location: "Earth" };const { name, age, location } = person;console.log(name); // Userconsole.log(age); // 30
This feature is particularly useful for working with APIs, configurations, or any scenario where you receive complex data structures.
Spread and Rest Operators
Section titled “Spread and Rest Operators”Spread Operator:
Section titled “Spread Operator:”The spread operator (...
) is used to expand arrays or objects into individual elements or properties.
const arr1 = [1, 2, 3];const arr2 = [4, 5, 6];const mergedArray = [...arr1, ...arr2];console.log(mergedArray); // [1, 2, 3, 4, 5, 6]
Rest Operator:
Section titled “Rest Operator:”The rest operator is used to collect multiple elements into an array or remaining properties into an object.
function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0);}console.log(sum(1, 2, 3, 4)); // 10
The dual functionalities of these operators make them powerful tools for working with variable-length data and simplifying operations on arrays or objects.
Default Parameters in Functions
Section titled “Default Parameters in Functions”Default parameters make it easier to set default values for function arguments. If an argument is not provided or is undefined
, the default value will be used.
function greet(name = "Guest") { return `Hello, ${name}!`;}console.log(greet()); // Hello, Guest!console.log(greet("User")); // Hello, User!