Mastering Modern JavaScript: ES6, ES7 and Beyond
Introduction to Modern JavaScript: ES6, ES7 and Beyond
JavaScript has come a long way since its inception. With the introduction of new versions of ECMAScript (ES) standards, JavaScript has evolved and improved, offering new features, syntax, and optimizations. This blog post will help you master modern JavaScript by covering the essentials of ES6, ES7, and beyond.
ES6 (ECMAScript 2015) Features
1. Let and Const
let
and const
are new ways to declare variables in JavaScript. let
is used when the variable’s value can change, while const
is used when the value should remain constant.
let a = 10;
a = 20; // This is allowed
const b = 30;
b = 40; // This will throw an error
2. Arrow Functions
Arrow functions provide a shorter syntax for declaring functions in JavaScript. They also have a lexical this
, meaning that they don’t create their own this
context.
// Traditional function syntax
function add(a, b) {
return a + b;
}
// Arrow function syntax
const add = (a, b) => a + b;
3. Template Literals
Template literals make it easy to create strings with embedded expressions, using backticks (`) and ${expression}
syntax.
const name = "John";
const age = 30;
// Old way of concatenating strings
const message = "My name is " + name + " and I am " + age + " years old.";
// Using template literals
const message = `My name is ${name} and I am ${age} years old.`;
4. Destructuring
Destructuring allows you to extract values from arrays or properties from objects into distinct variables.
// Array destructuring
const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a, b, c); // Output: 1 2 3
// Object destructuring
const person = {
name: "Alice",
age: 28,
};
const { name, age } = person;
console.log(name, age); // Output: Alice 28
5. Default Parameters
Default parameters allow you to set default values for function parameters.
function greet(name = "World") {
console.log(`Hello, ${name}!`);
}
greet("John"); // Output: Hello, John!
greet(); // Output: Hello, World!
6. Rest and Spread Operators
The rest operator (...
) allows you to represent an indefinite number of elements as an array. The spread operator is used to expand elements from an iterable.
// Rest operator
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // Output: 15
// Spread operator
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // Output: [1, 2, 3, 4, 5, 6]
ES7 (ECMAScript 2016) Features
1. Array.prototype.includes()
The includes()
method checks if an array contains a specified value, returning true
if it does and false
otherwise.
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(3)); // Output: true
console.log(numbers.includes(7)); // Output: false
2. Exponentiation Operator
The exponentiation operator (**
) is a shorthand for performing exponentiation.
console.log(2 ** 3); // Output: 8
console.log(4 ** 0.5); // Output: 2 (square root of 4)
ES8 (ECMAScript 2017) Features
1. Async/Await
async
and await
make it easier to work with promises in JavaScript, allowing you to write asynchronous code in a more synchronous manner.
const fetchData = async () => {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
};
fetchData();
2. Object.entries() and Object.values()
Object.entries()
and Object.values()
are methods that return an array of an object’s key-value pairs and an array of an object’s values, respectively.
const person = {
name: "Alice",
age: 28,
};
console.log(Object.entries(person)); // Output: [['name', 'Alice'], ['age', 28]]
console.log(Object.values(person)); // Output: ['Alice', 28]
3. String Padding
padStart()
and padEnd()
are string methods that pad the beginning or end of a string with a specified character.
const text = "42";
console.log(text.padStart(5, "0")); // Output: "00042"
console.log(text.padEnd(5, "0")); // Output: "42000"
ES9 (ECMAScript 2018) Features
1. Rest/Spread Properties for Objects
Rest and spread properties can be used with objects, just like with arrays.
const person = {
name: "Alice",
age: 28,
city: "New York",
};
const { city, ...rest } = person;
console.log(city); // Output: "New York"
console.log(rest); // Output: { name: 'Alice', age: 28 }
2. Asynchronous Iteration
Asynchronous iterators allow you to iterate over asynchronous data sources, such as read streams.
async function processStream(stream) {
for await (const chunk of stream) {
console.log(chunk);
}
}
3. Promise.prototype.finally()
The finally()
method is called when a promise is settled (either fulfilled or rejected), allowing you to run cleanup code regardless of the outcome.
fetch("https://api.example.com/data")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error))
.finally(() => console.log("Request completed."));
ES10 (ECMAScript 2019) Features
1. Array.prototype.flat() and Array.prototype.flatMap()
flat()
and flatMap()
are array methods that flatten nested arrays. flat()
flattens the array, while flatMap()
applies a function and then flattens the result.
const nested = [1, [2, 3], [4, [5]]];
console.log(nested.flat()); // Output: [1, 2, 3, 4, [5]]
console.log(nested.flat(2)); // Output: [1, 2, 3, 4, 5]
const names = ["John", "Jane"];
console.log(names.flatMap((name) => [name, name.toUpperCase()])); // Output: ['John', 'JOHN', 'Jane', 'JANE']
2. Object.fromEntries()
Object.fromEntries()
creates an object from an array of key-value pairs, which is the reverse of Object.entries()
.
const entries = [['name', 'Alice'], ['age', 28]];
const person = Object.fromEntries(entries);
console.log(person); // Output: { name: 'Alice', age: 28 }
3. String.prototype.trimStart() and String.prototype.trimEnd()
trimStart()
and trimEnd()
are string methods that remove whitespace from the beginning or end of a string, respectively.
const text = " Hello, world! ";
console.log(text.trimStart()); // Output: "Hello, world! "
console.log(text.trimEnd()); // Output: " Hello, world!"
ES11 (ECMAScript 2020) Features
1. Nullish Coalescing Operator
The nullish coalescing operator (??
) returns the right-hand operand if the left-hand operand is null
or undefined
, otherwise, it returns the left-hand operand.
const a = null;
const b = 42;
console.log(a ?? b); // Output: 42
console.log(a ?? "default"); // Output: "default"
2. Optional Chaining
Optional chaining (?.
) allows you to access properties of an object without having to check for the existence of the object.
const person = {
name: "Alice",
address: {
city: "New York",
},
};
console.log(person.address?.city); // Output: "New York"
console.log(person.job?.title); // Output: undefined
3. BigInt
BigInt
is a new numeric type that can represent integers of arbitrary size.
const largeNumber = 1234567890123456789012345678901234567890n;
console.log(largeNumber); // Output: 1234567890123456789012345678901234567890n
ES12 (ECMAScript 2021) Features
1. Logical Assignment Operators
Logical assignment operators combine logical operators with assignment, making the code more concise.
let a = 0;
let b = 42;
a ||= b; // Equivalent to: a || (a = b);
console.log(a); // Output: 42
a &&= b; // Equivalent to: a && (a = b);
console.log(a); // Output: 42
2. Numeric Separators
Numeric separators (_
) allow you to make large numbers more readable by separating groups of digits.
const largeNumber = 1_000_000;
console.log(largeNumber); // Output: 1000000
That covers most of the essential features introduced in modern JavaScript from ES6 to ES12. By understanding and mastering these features, you’ll be well-equipped to write clean, efficient, and maintainable JavaScript code.
Sharing is caring
Did you like what Mehul Mohan wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: