Mastering Modern JavaScript
🚀👩💻👨💻 JavaScript, the language that powers the web, continues to evolve and bring new features and improvements with each update. Whether you’re a seasoned developer or just starting your coding journey, staying up-to-date with the latest JavaScript features is essential. In this comprehensive cheat sheet, we’ll explore the key features introduced from ES6 to ES11, along with code examples and outputs.
Download the cheat here – Mastering Modern JavaScript.pdf
ES6 (ECMAScript 2015)
let
and const
In ES6, let
and const
were introduced to declare variables.
let variableName = 'This is a variable';
const constantValue = 'This cannot be changed';
console.log(variableName); // "This is a variable"
console.log(constantValue); // "This cannot be changed"
Arrow Functions
Arrow functions allow you to write shorter and more readable code when defining simple functions. They remove the need for the function
keyword and the return
statement in some cases.
Example without Arrow Function:
function add(a, b) {
return a + b;
}
Example with Arrow Function:
const add = (a, b) => a + b;
One of the most significant advantages of arrow functions is that they capture the surrounding this
value. In regular functions, the value of this
can change depending on how the function is called. Arrow functions, however, preserve the value of this
from their enclosing scope.
Example of this
in Regular Function:
function Counter() {
this.count = 0;
setInterval(function () {
this.count++; // This won't work as expected
console.log(this.count);
}, 1000);
}
In the above example, this.count
won’t behave as expected because this
inside the setInterval
callback refers to the global object, not the Counter
instance.
Example of this
with Arrow Function:
function Counter() {
this.count = 0;
setInterval(() => {
this.count++; // This works as expected
console.log(this.count);
}, 1000);
}
With the arrow function, this
correctly refers to the Counter
instance.
Template Literals
Template literals simplify string interpolation.
const name = 'John';
const greeting = `Hello, ${name}!`;
console.log(greeting); // "Hello, John!"
Destructuring Assignment
Destructuring allows you to extract values from objects and arrays.
const person = { name: 'Alice', age: 30 };
const { name, age } = person;
console.log(name); // "Alice"
console.log(age); // 30
Spread Operator
The spread operator can merge arrays and objects easily.
const array1 = [1, 2, 3];
const array2 = [...array1, 4, 5];
console.log(array2); // [1, 2, 3, 4, 5]
Rest Parameters
Rest parameters capture function arguments as an array.
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3)); // 6
Classes
ES6 introduced the class
syntax for creating constructor functions.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
const cat = new Animal('Whiskers');
cat.speak(); // "Whiskers makes a sound."
Promises
Promises simplify asynchronous operations.
const fetchData = () => {
return new Promise((resolve, reject) => {
// Async operation
if (success) {
resolve('Data fetched successfully');
} else {
reject('Error fetching data');
}
});
};
fetchData()
.then(data => {
console.log(data); // "Data fetched successfully"
})
.catch(error => {
console.error(error); // "Error fetching data"
});
ES7 (ECMAScript 2016)
Exponentiation Operator
The exponentiation operator **
simplifies calculations.
const squared = 2 ** 3;
console.log(squared); // 8
ES8 (ECMAScript 2017)
Async/Await
Async/await syntax simplifies working with promises.
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
fetchData()
.then(data => {
console.log(data); // Use the fetched data
})
.catch(error => {
console.error(error); // Handle errors
});
ES9 (ECMAScript 2018)
Rest/Spread Properties
Rest and spread properties simplify object manipulation.
const { x, y, ...rest } = { x: 1, y: 2, a: 3, b: 4 };
console.log(rest); // { a: 3, b: 4 }
Promise finally()
The finally()
method allows you to execute code regardless of promise resolution.
fetch('https://api.example.com/data')
.then(response => response.json())
.catch(error => console.error(error))
.finally(() => console.log('Request completed.'));
ES10 (ECMAScript 2019)
Array flat()
and flatMap()
flat()
and flatMap()
simplify array manipulation.
const arr = [1, 2, [3, [4, 5]]];
const flatArray = arr.flat(2);
console.log(flatArray); // [1, 2, 3, 4, 5]
const arr = [1, 2, 3];
const mappedArray = arr.flatMap(x => [x * 2]);
console.log(mappedArray); // [2, 4, 6]
Optional Catch Binding
You can omit the catch parameter.
try {
// Code that might throw an error
} catch {
// Handle the error without declaring a variable
}
Object.fromEntries()
Object.fromEntries()
converts an array of key-value pairs into an object.
const entries = [['a', 1], ['b', 2]];
const obj = Object.fromEntries(entries);
console.log(obj); // { a: 1, b: 2 }
💁 Check out our other articles😃
👉 Create Stunning Water Droplet Animation with JavaScript, HTML, and CSS: Step-by-Step Guide
👉 Creating a Toggle Switcher with Happy and Sad Faces using HTML, CSS, and JavaScript
ES11 (ES2020)
Optional Chaining (?.)
Optional chaining simplifies nested property access.
const user = {
address: {
street: '123 Main St',
city: 'Exampleville',
};
const city = user?.address?.city;
console.log(city); // "Exampleville"
Nullish Coalescing Operator (??)
The nullish coalescing operator provides a default value for null or undefined.
const defaultValue = 'Default Value';
const userInput = null;
const result = userInput ?? defaultValue;
console.log(result); // "Default Value"
Dynamic Import
Dynamic import allows you to load modules asynchronously.
const moduleSpecifier = './my-module.js';
import(moduleSpecifier)
.then(module => {
// Use the module
})
.catch(error => {
// Handle errors
});
BigInt
BigInt is a relatively new data type introduced in ES11 (ES2020) that allows you to work with arbitrarily large integers. BigInts can represent integers with precision far beyond the capabilities of standard JavaScript numbers.
const bigIntValue = 9007199254740991n;
console.log(bigIntValue); // 9007199254740991
GlobalThis
Before globalThis
, accessing the global object (e.g., window
in browsers, global
in Node.js) required knowing the specific environment, which could lead to non-portable code. With globalThis
, you can write code that works in different JavaScript environments without modifications.
You can use globalThis
to access the global object in various JavaScript environments, making your code more portable:
console.log(globalThis);
Here’s an example of using globalThis
to access the global object in a browser context:
globalThis.document.getElementById('my-element').textContent = 'Hello, globalThis!';
And in a Node.js context:
globalThis.console.log('Hello, globalThis in Node.js!');
This comprehensive cheat sheet covers the key features introduced in JavaScript from ES6 to ES11. Whether you’re building web applications or delving into server-side development with Node.js, mastering these features will empower you as a JavaScript developer.
Now, it’s your turn to dive in, explore these features, and apply them to your coding projects. Happy coding, and may your JavaScript journey be filled with creative and efficient solutions! 🚀👩💻👨💻
Resources
For more in-depth learning and advanced JavaScript topics, check out the following resources:
- Mozilla Developer Network (MDN) JavaScript Guide – MDN’s comprehensive guide to JavaScript, covering everything from basics to advanced topics.
- JavaScript.info – A detailed and up-to-date JavaScript tutorial that covers ES6 and beyond.
These resources will help you further expand your knowledge and master the art of JavaScript development. Happy coding!