JavaScript Modern JavaScript Syntax: ES6+ Cheat Sheet

JavaScript has evolved significantly over the years, and with the introduction of ECMAScript 6 (ES6) and subsequent versions, it has become more powerful, expressive, and developer - friendly. Modern JavaScript syntax, often referred to as ES6+, brings a plethora of new features and improvements that streamline code development and make it more readable and maintainable. This cheat - sheet blog aims to provide a comprehensive overview of the key features of ES6+ syntax, including their fundamental concepts, usage methods, common practices, and best practices.

Table of Contents

  1. Variable Declaration
  2. Arrow Functions
  3. Template Literals
  4. Destructuring Assignment
  5. Default Parameters
  6. Spread and Rest Operators
  7. Classes and Inheritance
  8. Promises and Async/Await
  9. Modules

1. Variable Declaration

Fundamental Concepts

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.

Usage Methods

// 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.

Common Practices

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.

Best Practices

Avoid using var in modern JavaScript, as it has function - scope and can lead to unexpected behavior.

2. Arrow Functions

Fundamental Concepts

Arrow functions provide a more concise syntax for writing function expressions. They do not have their own this, arguments, super, or new.target.

Usage Methods

// 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

Common Practices

Use arrow functions for short, simple functions, especially for callbacks.

Best Practices

Be careful when using arrow functions in methods where you rely on the this value, as arrow functions do not bind their own this.

3. Template Literals

Fundamental Concepts

Template literals allow you to embed expressions inside strings using backticks (`). This makes it easier to create dynamic strings.

Usage Methods

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.

Common Practices

Use template literals for string interpolation and multi - line strings instead of concatenation.

Best Practices

Keep expressions inside ${} simple for better readability.

4. Destructuring Assignment

Fundamental Concepts

Destructuring assignment allows you to extract values from arrays or objects and assign them to variables in a more concise way.

Usage Methods

// 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

Common Practices

Use destructuring when you need to extract specific values from arrays or objects.

Best Practices

You can use default values in destructuring to handle cases where a property is missing.

5. Default Parameters

Fundamental Concepts

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.

Usage Methods

function greet(name = 'Guest') {
    return `Hello, ${name}!`;
}

console.log(greet()); // Hello, Guest!
console.log(greet('Alice')); // Hello, Alice!

Common Practices

Use default parameters to make functions more flexible and reduce the need for conditional checks inside the function.

Best Practices

Set default values that make sense in the context of the function’s purpose.

6. Spread and Rest Operators

Fundamental Concepts

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.

Usage Methods

// 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

Common Practices

Use the spread operator for cloning arrays and objects, and the rest operator for functions that can accept a variable number of arguments.

Best Practices

Be aware of the performance implications when using the spread operator on large iterables.

7. Classes and Inheritance

Fundamental Concepts

ES6 introduced a class syntax that provides a more structured way to create objects and implement inheritance.

Usage Methods

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.

Common Practices

Use classes to create object - oriented code and inheritance to reuse and extend functionality.

Best Practices

Understand the difference between static and instance methods and use them appropriately.

8. Promises and Async/Await

Fundamental Concepts

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.

Usage Methods

// 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();

Common Practices

Use promises for handling asynchronous operations and async/await to make the code more readable and maintainable.

Best Practices

Always handle errors in promises and async/await functions to prevent unhandled promise rejections.

9. Modules

Fundamental Concepts

ES6 introduced a module system that allows you to split your code into multiple files and import/export functionality between them.

Usage Methods

// 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

Common Practices

Use modules to organize your code into smaller, reusable pieces.

Best Practices

Use named exports for most cases, and use default exports sparingly.

Conclusion

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.

References