ES6 introduced two new ways to declare variables: let
and const
. let
allows block - scoped variable declarations, while const
is used for declaring constants whose values cannot be reassigned.
// let example
function exampleLet() {
if (true) {
let x = 10;
console.log(x); // 10
}
// console.log(x); // ReferenceError: x is not defined
}
// const example
const PI = 3.14159;
// PI = 3; // TypeError: Assignment to constant variable.
Use const
by default when you don’t need to re - assign a variable. Reserve let
for cases where the variable needs to be updated.
Avoid using var
in modern JavaScript, as it has function - scope and can lead to unexpected behavior.
Arrow functions provide a more concise syntax for writing function expressions. They do not have their own this
, arguments
, super
, or new.target
.
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function
const addArrow = (a, b) => a + b;
console.log(add(3, 5)); // 8
console.log(addArrow(3, 5)); // 8
Use arrow functions for short, simple functions, especially for callbacks.
Be careful when using arrow functions in methods where you rely on the this
value, as arrow functions do not bind their own this
.
Template literals allow you to embed expressions inside strings using backticks (`). This makes it easier to create dynamic strings.
const name = 'John';
const age = 30;
const message = `My name is ${name} and I am ${age} years old.`;
console.log(message); // My name is John and I am 30 years old.
Use template literals for string interpolation and multi - line strings instead of concatenation.
Keep expressions inside ${}
simple for better readability.
Destructuring assignment allows you to extract values from arrays or objects and assign them to variables in a more concise way.
// Array destructuring
const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
// Object destructuring
const person = { firstName: 'Jane', lastName: 'Doe' };
const { firstName, lastName } = person;
console.log(firstName); // Jane
console.log(lastName); // Doe
Use destructuring when you need to extract specific values from arrays or objects.
You can use default values in destructuring to handle cases where a property is missing.
ES6 allows you to set default values for function parameters. If a parameter is not provided when the function is called, the default value will be used.
function greet(name = 'Guest') {
return `Hello, ${name}!`;
}
console.log(greet()); // Hello, Guest!
console.log(greet('Alice')); // Hello, Alice!
Use default parameters to make functions more flexible and reduce the need for conditional checks inside the function.
Set default values that make sense in the context of the function’s purpose.
The spread operator (...
) is used to expand an iterable (like an array or string) into individual elements. The rest operator is also written as (...
), but it is used to collect multiple elements into an array.
// Spread operator
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]
// Rest operator
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3)); // 6
Use the spread operator for cloning arrays and objects, and the rest operator for functions that can accept a variable number of arguments.
Be aware of the performance implications when using the spread operator on large iterables.
ES6 introduced a class syntax that provides a more structured way to create objects and implement inheritance.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Buddy');
dog.speak(); // Buddy barks.
Use classes to create object - oriented code and inheritance to reuse and extend functionality.
Understand the difference between static and instance methods and use them appropriately.
Promises are used to handle asynchronous operations in JavaScript. Async/await is a syntactic sugar built on top of promises that makes asynchronous code look more like synchronous code.
// Promise example
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data fetched successfully');
}, 1000);
});
}
// Async/await example
async function getData() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error(error);
}
}
getData();
Use promises for handling asynchronous operations and async/await to make the code more readable and maintainable.
Always handle errors in promises and async/await functions to prevent unhandled promise rejections.
ES6 introduced a module system that allows you to split your code into multiple files and import/export functionality between them.
// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
// main.js
import { add, subtract } from './math.js';
console.log(add(3, 5)); // 8
console.log(subtract(5, 3)); // 2
Use modules to organize your code into smaller, reusable pieces.
Use named exports for most cases, and use default exports sparingly.
Modern JavaScript syntax (ES6+) has brought a significant number of improvements to the language, making it more powerful, expressive, and developer - friendly. By mastering these features, you can write cleaner, more efficient, and maintainable code. This cheat - sheet provides a solid foundation for understanding and using the key aspects of ES6+ syntax, but there is always more to learn as the language continues to evolve.