ES6 Cheat Sheet

Here’s a cheat sheet for ES6 (ECMAScript 2015), which introduced significant enhancements to JavaScript:

Variable Declarations

// let and const
let variableName = value;
const constantName = value;

Arrow Functions

// Arrow Function
const add = (a, b) => a + b;

// Implicit Return
const square = x => x * x;

Destructuring Assignment

// Array Destructuring
const [a, b] = [1, 2];

// Object Destructuring
const { property1, property2 } = { property1: 'value1', property2: 'value2' };

Template Literals

// Template Literals
const name = 'John';
const greeting = `Hello, ${name}!`;

Default Parameters

// Default Parameters
const greet = (name = 'Guest') => `Hello, ${name}!`;

Spread and Rest Operators

// Spread Operator
const array1 = [1, 2, 3];
const array2 = [...array1, 4, 5];

// Rest Parameter
const sum = (...numbers) => numbers.reduce((acc, num) => acc + num, 0);

Classes

// Classes
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

const cat = new Animal('Cat');
cat.speak();

Promises

// Promises
const fetchData = () => {
  return new Promise((resolve, reject) => {
    // Async operation
    if (success) {
      resolve(data);
    } else {
      reject(error);
    }
  });
};

fetchData()
  .then(data => console.log(data))
  .catch(error => console.error(error));

Modules

// Modules (ES6 Module Syntax)
// Exporting: export { variable, function };
// Importing: import { variable, function } from 'module';

Object Enhancements

// Shorthand Property Names
const name = 'John';
const age = 30;
const person = { name, age };

// Computed Property Names
const dynamicKey = 'property';
const dynamicObject = { [dynamicKey]: 'value' };

Map and Set

// Map
const map = new Map();
map.set(key, value);
const retrievedValue = map.get(key);

// Set
const set = new Set();
set.add(value);
const hasValue = set.has(value);

async/await

// async/await
const fetchData = async () => {
  try {
    const data = await fetch('https://api.example.com/data');
    const result = await data.json();
    console.log(result);
  } catch (error) {
    console.error(error);
  }
};

fetchData();

This cheat sheet covers some of the key features introduced in ES6. Keep in mind that ES6 is a significant upgrade to JavaScript, and there are more features and improvements beyond what’s listed here.