JavaScript ES6 in a Nutshell: A Quick Overview Cheatsheet

·

8 min read

JavaScript ES6 in a Nutshell: A Quick Overview Cheatsheet

ECMAScript 2015 or ES2015 is a significant update to the JavaScript programming language. It is the first major update to the language since ES5 which was standardized in 2009. Therefore, ES2015 is often called ES6.

ES6 brings many new features to JavaScript including support for modules, classes, arrow functions, and more. In this tutorial, we will go over some of the most important features of ES6. By the end of this tutorial, you should have a good understanding of what's new in JavaScript and be able to start using these new features in your own code.

If you're already familiar with JavaScript, then you can probably skip ahead to the section on modules. Otherwise, let's start with a review of some of the basic JavaScript features that ES6 builds upon.

JavaScript Review

Before we dive into the new features in ES6, let's review some of the basics of JavaScript. If you're already familiar with JavaScript, feel free to skip this section.

Variables

In JavaScript, variables are used to store values. Values can be strings, numbers, arrays, objects, or any other data type.

Variables are declared using the var keyword:

var myName = "John";
var myAge = 25;

myName is a variable that stores the string "John". myAge is a variable that stores the number 25.

You can also declare multiple variables at once:

var myName = "John",
myAge = 25,
myHeight = 70;

You can declare variables without assigning them a value. In this case, the variable will be given the value undefined:

var myName; // undefined

You can also declare variables and assign them a value in the same statement:

var myName = "John"; // "John"

Data Types

JavaScript has seven data types:

  1. string,
  2. number,
  3. boolean,
  4. null,
  5. undefined,
  6. object,
  7. symbol (new in ES6).
  8. Strings

Strings are used to store text and are surrounded by either single or double quotes:

var myString = "This is a string"; // double quotes
var myString = 'This is also a string'; // single quotes

Numbers

Numbers are used to storing numeric values. They can be positive or negative, and can be integers or floats:

var myNum = 5; // integer
var myNum = 5.5; // float

Booleans

Booleans are used to store true or false values:

var myBool = true; // true
var myBool = false; // false

Null

Null is used to represent no value:

var myNull = null;

Undefined

Undefined is used when a variable has not been assigned a value:

var myUndefined; // undefined

Objects

Objects are used to store data in key/value pairs. The keys are always strings, but the ` values can be any data type:

var myObj = {
    name: "John",
    age: 25,
    isMarried: false
  };

Arrays

Arrays are used to store ordered lists of values. The values in an array can be any data type, and they are accessed by their index number:

var myArray = ["string", 2, true]; // ["string", 2, true]

Symbols (new in ES6)

Symbols (new in ES6) are unique identifiers and are used as property keys for objects:

var mySymbol = Symbol(); // Symbol()

Functions

JavaScript functions are blocks of code that can be executed when called. Functions can take zero or more parameters. The code inside a function is executed when the function is called:

function myFunction(myParam) {
    // code to be executed
}

Functions can also be defined using the arrow syntax (new in ES6):

const myFunction = (myParam) => {
    // code to be executed
}

ES6 Features

Now that we've reviewed some of the basics of JavaScript, let's look at some of the new features in ES6.

Let and Const

In JavaScript, variables are declared using the var keyword. Variables declared with var are globally scoped or function scoped. That means they can be accessed from anywhere in your code. ES6 introduced two new keywords for declaring variables: let and const. Variables declared with let are block-scoped. That means they can only be accessed from within the block they were declared in. For example:

if (true) {
    let myVar = "foo";
}
console.log(myVar); // ReferenceError: myVar is not defined

myVar is only accessible within the if block. Trying to access it outside of that block will result in an error. Variables declared with const are also block-scoped, but they cannot be reassigned. That means once a variable is declared with const, its value cannot be changed:

const myVar = "foo";
myVar = "bar"; // TypeError: Assignment to constant variable.

If you try to reassign a const variable, you'll get an error. Unlike variables declared with var or let, constants cannot be re-declared:

const myVar = "foo";
const myVar = "bar"; // SyntaxError: Identifier 'myVar' has already been declared

Modules

JavaScript modules are a way to modularize your code. Modules are small units of independent, reusable code. They can be used as libraries or packages and can be imported into other files for use. Modules are declared using the module keyword:

// my-module.js
export const MY_CONSTANT = "value";
// app.js
import { MY_CONSTANT } from './my-module';
console.log(MY_CONSTANT); // value

Classes (new in ES6)

JavaScript classes are a way to create objects. Objects created from a class have the same properties and methods. Classes are declared using the class keyword:

class Car {
    // code goes here
}

Classes can be extended to create more specific objects, and can be instantiated to create objects:

class Car {
    // code goes here
}
class SUV extends Car {
  // code goes here
}
const mySUV = new SUV();

Destructuring (new in ES6)

JavaScript destructuring is a way to extract data from arrays or objects into individual variables. It is declared using curly braces ({}):

const myObj = { name: "John", age: 25 };
const { name, age } = myObj; // name = "John", age = 25
const myArray = ["a", "b", "c"];
const { 0: first, 2: third } = myArray; // first = "a", third = "c"

Rest and Spread Operator (new in ES6)

The JavaScript rest operator allows you to represent an indefinite number of arguments as an array. It is declared using three dots (...) followed by the name of the array:

function myFunction(...theArgs) {
    // code goes here
}

The JavaScript spread operator allows you to expand arrays or objects into multiple variables. It is declared using three dots (...):

const myArray = ["a", "b", "c"];
const { 0: first, 2: third } = myArray; // first = "a", third = "c"

Promises (new in ES6)

JavaScript promises are a way to handle asynchronous code. A promise represents the result of an asynchronous operation. Promises can be either resolved or rejected. If a promise is resolved, it means the async operation was successful. If a promise is rejected, it means the async operation failed.

const myPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Success!"); // resolve the promise with "Success!"
    }, 1000);
});
myPromise.then((successMessage) => {
    console.log(successMessage); // will print "Success!" after 1 second
});

Map and Set (new in ES6)

JavaScript maps are a new data structure that allows you to map keys to values. Maps are declared using the new Map() syntax:

const myMap = new Map();
myMap.set("key1", "value1"); // set key1 to value1
myMap.set("key2", "value2"); // set key2 to value2
console.log(myMap.get("key1")); // will print "value1"
console.log(myMap.get("key2")); // will print "value2"

JavaScript sets are a new data structure that allows you to store unique values. Sets are declared using the new Set() syntax:

const mySet = new Set();
mySet.add("value1"); // add value1 to the set
mySet.add("value2"); // add value2 to the set
mySet.add("value3"); // add value3 to the set
console.log(mySet.has("value1")); // will print true
console.log(mySet.has("value4")); // will print false

Generators (new in ES6)

JavaScript generators are a new type of function that allows you to create values that can be iterated over. Generators are declared using the function* syntax:

function* myGenerator() {
    // code goes here
}
const myIterator = myGenerator();

For… of (new in ES6)

The for…of loop is a new feature in ES6 that allows you to iterate over arrays, strings, or other iterable objects: const myArray = ["a", "b", "c"]; for (const item of myArray) { console.log(item); // a b c }

Iterator Protocol (new in ES6)

JavaScript’s iterator protocol allows objects to define how they will be iterated over. An object that implements the iterator protocol must have a method called Symbol. iterator:

const myIterableObj = {
     // code goes here
}
myIterableObj.Symbol.iterator = function () {
     // code goes here
};

Template Strings (new in ES6)

JavaScript template strings are a new way to create strings. Template strings are declared using the backtick character (`):

const myString = `This is a template string`;
console.log(myString); // will print "This is a template string"

Arrow Functions (new in ES6)

JavaScript arrow functions are a new way to create functions. Arrow functions are declared using the => syntax:

const myFunction = () => {
    // code goes here
};
const myOtherFunction = (param1, param2) => {
    // code goes here
};
console.log(myFunction()); // will print undefined
console.log(myOtherFunction(1, 2)); // will print undefined

Classes, restructuring the rest and spread operator, promises, maps and sets, generators, template strings, and arrow functions are all new in ES6. These features can make your JavaScript code more concise and easier to read. That's why we're providing this tutorial so you can learn all about them!

Thanks for reading!

Did you find this article valuable?

Support Atif Riaz by becoming a sponsor. Any amount is appreciated!