- Arrow Functions
- A new
this
scope - Promises
- Generators
let
andconst
- Classes
- Modules
- Template Literals
- Default parameters
- The spread operator
- Destructuring assignments
- Enhanced Object Literals
- For-of loop
- Map and Set
- New String methods
- New Object methods
ECMAScript 2015, also known as ES6, is a fundamental version of the ECMAScript standard.
Published 4 years after the latest standard revision, ECMAScript 5.1, it also marked the switch from edition number to year number.
So it should not be named as ES6 (although everyone calls it as such) but ES2015 instead.
ES5 was 10 years in the making, from 1999 to 2009, and as such it was also a fundamental and very important revision of the language, but now much time has passed that it’s not worth discussing how pre-ES5 code worked.
Since this long time passed between ES5.1 and ES6, the release is full of important new features and major changes in suggested best practices in developing JavaScript programs. To understand how fundamental ES2015 is, just keep in mind that with this version, the specification document went from 250 pages to ~600.
This article describes the most important changes.
Arrow Functions
Arrow functions since their introduction changed how most JavaScript code looks (and works).
Visually, it’s a simple and welcome change, from:
const something = function something() {
//...
}
to
const something = () => {
//...
}
And if the function body is a one-liner, just:
const something = () => doSomething()
Also, if you have a single parameter, you could write:
const something = param => doSomething(param)
This is not a breaking change, regular function
s will continue to work just as before.
A new this
scope
The this
scope with arrow functions is inherited from the context.
With regular function
s this
always refers to the nearest function, while with arrow functions this problem is removed, and you won’t need to write var that = this
ever again.
Promises
Promises (check the full guide to promises) allow us to eliminate the famous “callback hell”, although they introduce a bit more complexity (which has been solved in ES2017 with async
, a higher level construct).
Promises have been used by JavaScript developers well before ES2015, with many different libraries implementations (e.g. jQuery, q, deferred.js, vow…), and the standard put a common ground across differences.
By using promises you can rewrite this code
setTimeout(function() {
console.log('I promised to run after 1s')
setTimeout(function() {
console.log('I promised to run after 2s')
}, 1000)
}, 1000)
as
const wait = () => new Promise((resolve, reject) => {
setTimeout(resolve, 1000)
})
wait().then(() => {
console.log('I promised to run after 1s')
return wait()
})
.then(() => console.log('I promised to run after 2s'))
Generators
Generators are a special kind of function with the ability to pause itself, and resume later, allowing other code to run in the meantime.
See the full JavaScript Generators Guide for a detailed explanation of the topic.
let
and const
var
is traditionally function scoped.
let
is a new variable declaration which is block scoped.
This means that declaring let
variables in a for loop, inside an if or in a plain block is not going to let that variable “escape” the block, while var
s are hoisted up to the function definition.
const
is just like let
, but immutable.
In JavaScript moving forward, you’ll see little to no var
declarations any more, just let
and const
.
const
in particular, maybe surprisingly, is very widely used nowadays with immutability being very popular.
Classes
Traditionally JavaScript is the only mainstream language with prototype-based inheritance. Programmers switching to JS from class-based language found it puzzling, but ES2015 introduced classes, which are just syntactic sugar over the inner working, but changed a lot how we build JavaScript programs.
Now inheritance is very easy and resembles other object-oriented programming languages:
class Person {
constructor(name) {
this.name = name
}
hello() {
return 'Hello, I am ' + this.name + '.'
}
}
class Actor extends Person {
hello() {
return super.hello() + ' I am an actor.'
}
}
var tomCruise = new Actor('Tom Cruise')
tomCruise.hello()
(the above program prints “Hello, I am Tom Cruise. I am an actor.”)
Classes do not have explicit class variable declarations, but you must initialize any variable in the constructor.
Constructor
Classes have a special method called constructor
which is called when a class is initialized via new
.
Super
The parent class can be referenced using super()
.
Getters and setters
A getter for a property can be declared as
class Person {
get fullName() {
return `${this.firstName} ${this.lastName}`
}
}
Setters are written in the same way:
class Person {
set age(years) {
this.theAge = years
}
}
Modules
Before ES2015, there were at least 3 major modules competing standards, which fragmented the community:
- AMD
- RequireJS
- CommonJS
ES2015 standardized these into a common format.
Importing modules
Importing is done via the import ... from ...
construct:
import * from 'mymodule'
import React from 'react'
import { React, Component } from 'react'
import React as MyLibrary from 'react'
Exporting modules
You can write modules and export anything to other modules using the export
keyword:
export var number = 2
export function bar() { /* ... */ }
Template Literals
Template literals are a new syntax to create strings:
const aString = `A string`
They provide a way to embed expressions into strings, effectively inserting the values, by using the ${a_variable}
syntax:
const joe = 'test'
const string = `something ${joe}` //something test
You can perform more complex expressions as well:
const string = `something ${1 + 2 + 3}`
const string2 = `something ${doSomething() ? 'x' : 'y' }`
and strings can span over multiple lines:
const string3 = `Hey
this
string
is awesome!`
Compare how we used to do multiline strings pre-ES2015:
var str = 'One\n' +
'Two\n' +
'Three'
Default parameters
Functions now support default parameters:
const someFunction = function(index = 0, testing = true) { /* ... */ }
someFunction()
The spread operator
You can expand an array, an object or a string using the spread operator ...
.
Let’s start with an array example. Given
const a = [1, 2, 3]
you can create a new array using
const b = [...a, 4, 5, 6]
You can also create a copy of an array using
const c = [...a]
This works for objects as well. Clone an object with:
const newObj = { ...oldObj }
Using strings, the spread operator creates an array with each char in the string:
const hey = 'hey'
const arrayized = [...hey] // ['h', 'e', 'y']
This operator has some pretty useful applications. The most important one is the ability to use an array as function argument in a very simple way:
const f = (arg1, arg2) => {}
const a = [1, 2]
f(...a)
(in the past you could do this using f.apply(null, a)
but that’s not as nice and readable)
Destructuring assignments
Given an object, you can extract just some values and put them into named variables:
const person = {
firstName: 'Tom',
lastName: 'Cruise',
actor: true,
age: 54, //made up
}
const {firstName: name, age} = person
name
and age
contain the desired values.
The syntax also works on arrays:
const a = [1,2,3,4,5]
const [first, second] = a
This statement creates 3 new variables by getting the items with index 0, 1, 4 from the array a
:
const [first, second, , , fifth] = a
Enhanced Object Literals
In ES2015 Object Literals gained superpowers.
Simpler syntax to include variables
Instead of doing
const something = 'y'
const x = {
something: something
}
you can do
const something = 'y'
const x = {
something
}
Prototype
A prototype can be specified with
const anObject = { y: 'y' }
const x = {
__proto__: anObject
}
super()
const anObject = { y: 'y', test: () => 'zoo' }
const x = {
__proto__: anObject,
test() {
return super.test() + 'x'
}
}
x.test() //zoox
Dynamic properties
const x = {
['a' + '_' + 'b']: 'z'
}
x.a_b //z
For-of loop
ES5 back in 2009 introduced forEach()
loops. While nice, they offered no way to break, like for
loops always did.
ES2015 introduced the for-of
loop, which combines the conciseness of forEach
with the ability to break:
//iterate over the value
for (const v of ['a', 'b', 'c']) {
console.log(v);
}
//get the index as well, using `entries()`
for (const [i, v] of ['a', 'b', 'c'].entries()) {
console.log(i, v);
}
Map and Set
Map and Set (and their respective garbage collected WeakMap and WeakSet) are the official implementations of two very popular data structures.
New String methods
Any string value got some new instance methods:
repeat()
repeats the strings for the specificed number of times:'Ho'.repeat(3) //HoHoHo
codePointAt()
handles retrieving the Unicode code of characters that cannot be represented by a single 16-bit UTF-16 unit, but need 2 instead
New Object methods
ES6 introduced several static methods under the Object namespace:
Object.is()
determines if two values are the same valueObject.assign()
used to shallow copy an objectObject.setPrototypeOf
sets an object prototype
Download my free JavaScript Beginner's Handbook
More js tutorials:
- Things to avoid in JavaScript (the bad parts)
- Deferreds and Promises in JavaScript (+ Ember.js example)
- How to upload files to the server using JavaScript
- JavaScript Coding Style
- An introduction to JavaScript Arrays
- Introduction to the JavaScript Programming Language
- The Complete ECMAScript 2015-2019 Guide
- Understanding JavaScript Promises
- The Lexical Structure of JavaScript
- JavaScript Types
- JavaScript Variables
- A list of sample Web App Ideas
- An introduction to Functional Programming with JavaScript
- Modern Asynchronous JavaScript with Async and Await
- JavaScript Loops and Scope
- The Map JavaScript Data Structure
- The Set JavaScript Data Structure
- A guide to JavaScript Template Literals
- Roadmap to Learn JavaScript
- JavaScript Expressions
- Discover JavaScript Timers
- JavaScript Events Explained
- JavaScript Loops
- Write JavaScript loops using map, filter, reduce and find
- The JavaScript Event Loop
- JavaScript Functions
- The JavaScript Glossary
- JavaScript Closures explained
- A tutorial to JavaScript Arrow Functions
- A guide to JavaScript Regular Expressions
- How to check if a string contains a substring in JavaScript
- How to remove an item from an Array in JavaScript
- How to deep clone a JavaScript object
- Introduction to Unicode and UTF-8
- Unicode in JavaScript
- How to uppercase the first letter of a string in JavaScript
- How to format a number as a currency value in JavaScript
- How to convert a string to a number in JavaScript
- this in JavaScript
- How to get the current timestamp in JavaScript
- JavaScript Strict Mode
- JavaScript Immediately-invoked Function Expressions (IIFE)
- How to redirect to another web page using JavaScript
- How to remove a property from a JavaScript object
- How to append an item to an array in JavaScript
- How to check if a JavaScript object property is undefined
- Introduction to ES Modules
- Introduction to CommonJS
- JavaScript Asynchronous Programming and Callbacks
- How to replace all occurrences of a string in JavaScript
- A quick reference guide to Modern JavaScript Syntax
- How to trim the leading zero in a number in JavaScript
- How to inspect a JavaScript object
- The definitive guide to JavaScript Dates
- A Moment.js tutorial
- Semicolons in JavaScript
- The JavaScript Arithmetic operators
- The JavaScript Math object
- Generate random and unique strings in JavaScript
- How to make your JavaScript functions sleep
- JavaScript Prototypal Inheritance
- JavaScript Exceptions
- How to use JavaScript Classes
- The JavaScript Cookbook
- Quotes in JavaScript
- How to validate an email address in JavaScript
- How to get the unique properties of a set of objects in a JavaScript array
- How to check if a string starts with another in JavaScript
- How to create a multiline string in JavaScript
- The ES6 Guide
- How to get the current URL in JavaScript
- The ES2016 Guide
- How to initialize a new array with values in JavaScript
- The ES2017 Guide
- The ES2018 Guide
- How to use Async and Await with Array.prototype.map()
- Async vs sync code
- How to generate a random number between two numbers in JavaScript
- HTML Canvas API Tutorial
- How to get the index of an iteration in a for-of loop in JavaScript
- What is a Single Page Application?
- An introduction to WebAssembly
- Introduction to JSON
- The JSONP Guide
- Should you use or learn jQuery in 2020?
- How to hide a DOM element using plain JavaScript
- How to merge two objects in JavaScript
- How to empty a JavaScript array
- How to encode a URL with JavaScript
- How to set default parameter values in JavaScript
- How to sort an array of objects by a property value in JavaScript
- How to count the number of properties in a JavaScript object
- call() and apply() in JavaScript
- Introduction to PeerJS, the WebRTC library
- Work with objects and arrays using Rest and Spread
- Destructuring Objects and Arrays in JavaScript
- The definitive guide to debugging JavaScript
- The TypeScript Guide
- Dynamically select a method of an object in JavaScript
- Passing undefined to JavaScript Immediately-invoked Function Expressions
- Loosely typed vs strongly typed languages
- How to style DOM elements using JavaScript
- Casting in JavaScript
- JavaScript Generators Tutorial
- The node_modules folder size is not a problem. It's a privilege
- How to solve the unexpected identifier error when importing modules in JavaScript
- How to list all methods of an object in JavaScript
- The String replace() method
- The String search() method
- How I run little JavaScript snippets
- The ES2019 Guide
- The String charAt() method
- The String charCodeAt() method
- The String codePointAt() method
- The String concat() method
- The String endsWith() method
- The String includes() method
- The String indexOf() method
- The String lastIndexOf() method
- The String localeCompare() method
- The String match() method
- The String normalize() method
- The String padEnd() method
- The String padStart() method
- The String repeat() method
- The String slice() method
- The String split() method
- The String startsWith() method
- The String substring() method
- The String toLocaleLowerCase() method
- The String toLocaleUpperCase() method
- The String toLowerCase() method
- The String toString() method
- The String toUpperCase() method
- The String trim() method
- The String trimEnd() method
- The String trimStart() method
- Memoization in JavaScript
- The String valueOf() method
- JavaScript Reference: String
- The Number isInteger() method
- The Number isNaN() method
- The Number isSafeInteger() method
- The Number parseFloat() method
- The Number parseInt() method
- The Number toString() method
- The Number valueOf() method
- The Number toPrecision() method
- The Number toExponential() method
- The Number toLocaleString() method
- The Number toFixed() method
- The Number isFinite() method
- JavaScript Reference: Number
- JavaScript Property Descriptors
- The Object assign() method
- The Object create() method
- The Object defineProperties() method
- The Object defineProperty() method
- The Object entries() method
- The Object freeze() method
- The Object getOwnPropertyDescriptor() method
- The Object getOwnPropertyDescriptors() method
- The Object getOwnPropertyNames() method
- The Object getOwnPropertySymbols() method
- The Object getPrototypeOf() method
- The Object is() method
- The Object isExtensible() method
- The Object isFrozen() method
- The Object isSealed() method
- The Object keys() method
- The Object preventExtensions() method
- The Object seal() method
- The Object setPrototypeOf() method
- The Object values() method
- The Object hasOwnProperty() method
- The Object isPrototypeOf() method
- The Object propertyIsEnumerable() method
- The Object toLocaleString() method
- The Object toString() method
- The Object valueOf() method
- JavaScript Reference: Object
- JavaScript Assignment Operator
- JavaScript Internationalization
- JavaScript typeof Operator
- JavaScript new Operator
- JavaScript Comparison Operators
- JavaScript Operators Precedence Rules
- JavaScript instanceof Operator
- JavaScript Statements
- JavaScript Scope
- JavaScript Type Conversions (casting)
- JavaScript Equality Operators
- The JavaScript if/else conditional
- The JavaScript Switch Conditional
- The JavaScript delete Operator
- JavaScript Function Parameters
- The JavaScript Spread Operator
- JavaScript Return Values
- JavaScript Logical Operators
- JavaScript Ternary Operator
- JavaScript Recursion
- JavaScript Object Properties
- JavaScript Error Objects
- The JavaScript Global Object
- The JavaScript filter() Function
- The JavaScript map() Function
- The JavaScript reduce() Function
- The JavaScript `in` operator
- JavaScript Operators
- How to get the value of a CSS property in JavaScript
- How to add an event listener to multiple elements in JavaScript
- JavaScript Private Class Fields
- How to sort an array by date value in JavaScript
- JavaScript Public Class Fields
- JavaScript Symbols
- How to use the JavaScript bcrypt library
- How to rename fields when using object destructuring
- How to check types in JavaScript without using TypeScript
- How to check if a JavaScript array contains a specific value
- What does the double negation operator !! do in JavaScript?
- Which equal operator should be used in JavaScript comparisons? == vs ===
- Is JavaScript still worth learning?
- How to return the result of an asynchronous function in JavaScript
- How to check if an object is empty in JavaScript
- How to break out of a for loop in JavaScript
- How to add item to an array at a specific index in JavaScript
- Why you should not modify a JavaScript object prototype
- What's the difference between using let and var in JavaScript?
- Links used to activate JavaScript functions
- How to join two strings in JavaScript
- How to join two arrays in JavaScript
- How to check if a JavaScript value is an array?
- How to get last element of an array in JavaScript?
- How to send urlencoded data using Axios
- How to get tomorrow's date using JavaScript
- How to get yesterday's date using JavaScript
- How to get the month name from a JavaScript date
- How to check if two dates are the same day in JavaScript
- How to check if a date refers to a day in the past in JavaScript
- JavaScript labeled statements
- How to wait for 2 or more promises to resolve in JavaScript
- How to get the days between 2 dates in JavaScript
- How to upload a file using Fetch
- How to format a date in JavaScript
- How to iterate over object properties in JavaScript
- How to calculate the number of days between 2 dates in JavaScript
- How to use top-level await in ES Modules
- JavaScript Dynamic Imports
- JavaScript Optional Chaining
- How to replace white space inside a string in JavaScript
- JavaScript Nullish Coalescing
- How to flatten an array in JavaScript
- This decade in JavaScript
- How to send the authorization header using Axios
- List of keywords and reserved words in JavaScript
- How to convert an Array to a String in JavaScript
- How to remove all the node_modules folders content
- How to remove duplicates from a JavaScript array
- Let vs Const in JavaScript
- The same POST API call in various JavaScript libraries
- How to get the first n items in an array in JS
- How to divide an array in multiple equal parts in JS
- How to slow down a loop in JavaScript
- How to load an image in an HTML canvas
- How to cut a string into words in JavaScript
- How to divide an array in half in JavaScript
- How to write text into to an HTML canvas
- How to remove the last character of a string in JavaScript
- How to remove the first character of a string in JavaScript
- How to fix the TypeError: Cannot assign to read only property 'exports' of object '#<Object>' error
- How to create an exit intent popup
- How to check if an element is a descendant of another
- How to force credentials to every Axios request
- How to solve the "is not a function" error in JavaScript
- Gatsby, how to change the favicon
- Loading an external JS file using Gatsby
- How to detect dark mode using JavaScript
- Parcel, how to fix the `regeneratorRuntime is not defined` error
- How to detect if an Adblocker is being used with JavaScript
- Object destructuring with types in TypeScript
- The Deno Handbook: a concise introduction to Deno 🦕
- How to get the last segment of a path or URL using JavaScript
- How to shuffle elements in a JavaScript array
- How to check if a key exists in a JavaScript object
- Event bubbling and event capturing
- event.stopPropagation vs event.preventDefault() vs. return false in DOM events
- Primitive types vs objects in JavaScript
- How can you tell what type a value is, in JavaScript?
- How to return multiple values from a function in JavaScript
- Arrow functions vs regular functions in JavaScript
- In which ways can we access the value of a property of an object?
- What is the difference between null and undefined in JavaScript?
- What's the difference between a method and a function?
- What are the ways we can break out of a loop in JavaScript?
- The JavaScript for..of loop
- What is object destructuring in JavaScript?
- What is hoisting in JavaScript?
- How to change commas into dots with JavaScript
- The importance of timing when working with the DOM
- How to reverse a JavaScript array
- How to check if a value is a number in JavaScript
- How to accept unlimited parameters in a JavaScript function
- JavaScript Proxy Objects
- Event delegation in the browser using vanilla JavaScript
- The JavaScript super keyword
- Introduction to XState
- Are values passed by reference or by value in JavaScript?
- Custom events in JavaScript
- Custom errors in JavaScript
- Namespaces in JavaScript
- A curious usage of commas in JavaScript
- Chaining method calls in JavaScript
- How to handle promise rejections
- How to swap two array elements in JavaScript
- How I fixed a "cb.apply is not a function" error while using Gitbook
- How to add an item at the beginning of an array in JavaScript
- Gatsby, fix the "cannot find module gatsby-cli/lib/reporter" error
- How to get the index of an item in a JavaScript array
- How to test for an empty object in JavaScript
- How to destructure an object to existing variables in JavaScript
- The Array JavaScript Data Structure
- The Stack JavaScript Data Structure
- JavaScript Data Structures: Queue
- JavaScript Data Structures: Set
- JavaScript Data Structures: Dictionaries
- JavaScript Data Structures: Linked lists
- JavaScript, how to export a function
- JavaScript, how to export multiple functions
- JavaScript, how to exit a function
- JavaScript, how to find a character in a string
- JavaScript, how to filter an array
- JavaScript, how to extend a class
- JavaScript, how to find duplicates in an array
- JavaScript, how to replace an item of an array
- JavaScript Algorithms: Linear Search
- JavaScript Algorithms: Binary Search
- JavaScript Algorithms: Selection Sort
- JavaScript Algorithms: Quicksort
- JavaScript Algorithms: Merge Sort
- JavaScript Algorithms: Bubble Sort