Javascript ES6
ECMAScript 2015 is the second significant update to JavaScript.
ECMAScript 2015 is commonly referred to as ES6 and ECMAScript 6.
This section talks about the key aspects of ES6.
New Features in ES6
JavaScript let
The let
keyword lets you create a variable that only exists within a specific block of code.
Learn more about the let
keyword in the chapter on JavaScript Let.
JavaScript const
The const
word lets you set up a constant in JavaScript, which means a variable that won't change its value.
Constants are like 'let' variables, but their values cannot be altered.
Learn more about the const
keyword in the section on JavaScript Const.
Arrow Functions
Arrow functions make it easy to write concise function expressions using a shorter syntax.
You can exclude the function
and return
keywords, as well as the curly brackets.
Arrow functions don't have their own this
. They aren't ideal for defining object methods.
Arrow functions don't get moved up in code. You need to create them before using them.
Using const
is better than var
because a function expression remains constant.
If your function consists of only one statement, you can skip using the return
keyword and curly brackets. It's a good practice to include them, though.
Explore further details on Arrow Functions in this section: JavaScript Arrow Function.
The Spread (...) Operator
The ... operator helps to spread out a list or array into individual elements.
The "..." operator lets you take items from a list and use them as separate inputs for functions.
The For/Of Loop
The JavaScript code using for/of
helps to go through the values of objects that can be iterated.
The for/of
allows you to go through collections that can be looped over, like Arrays, Strings, Maps, NodeLists, and others.
The syntax for the for/of
loop is as follows:
for (variable of iterable) {
}
Variable - Each time it loops, the next property's value is given to the variable. You can define a variable using const
, let
, or var
.
Iterable - An object with properties that can be iterated over.
Looping over an Array
Looping over a String
Find additional information in this section: JavaScript Loop For/In/Of.
JavaScript Maps
Using an Object as a key is a crucial feature in Maps.
Discover more about Map objects and understand the distinction between a Map and an Array in the chapter: JavaScript Maps.
JavaScript Sets
Find out more about Set objects in the chapter: JavaScript Sets.
JavaScript Classes
JavaScript Classes act as blueprints for creating JavaScript Objects.
Utilize the term class
to form a class.
Always include a function called constructor()
:
Syntax
class ClassName {
constructor() { ... }
}
Example
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
The code snippet provided defines a class called "Car."
The class initially has two properties: "name" and "year."
A JavaScript class is not the same as an object.
It's a template for JavaScript objects.
Using a Class
When you possess a class, you can utilize it to generate objects:
Explore further details about classes in the chapter on JavaScript Classes by visiting this link.
JavaScript Promises
A Promise in JavaScript connects "Producing Code" with "Consuming Code."
"Writing code" may require time, and other parts of code have to wait for its outcome.
Promise Syntax
const myPromise = new Promise(function(myResolve, myReject) {
myResolve();
myReject();
});
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
Discover additional information about Promises in the chapter: JavaScript Promises.
The Symbol Type
A JavaScript Symbol is a basic type, similar to Number, String, or Boolean.
It signifies a special "secret" code that cannot be unintentionally reached by any other code.
For example, if various programmers want to include a person.id attribute to a person object from someone else's code, they might blend their values together.
Creating unique identifiers is made simple by using Symbol().
Note
Symbols are always one of a kind.
If you make two symbols with the identical description, they will possess distinct values:
Symbol("id") == Symbol("id");
Default Parameter Values
ES6 enables setting default values for function parameters.
Function Rest Parameter
The rest parameter (…) enables a function to handle a variable number of arguments as an array.
String.includes()
The includes()
function checks if a given string has a particular value. It gives back true
if the string contains the value and false
if it doesn't.
String.startsWith()
The startsWith()
function checks if a given string starts with a particular value.It gives back true
if the string starts with the given value, and false
if it doesn't.
String.endsWith()
The endsWith()
function checks if the end of a given string matches a particular value. It returns true
if there is a match, and false
otherwise.
Array.from()
The function Array.from()
makes an array from an object that has a length property or any object you can loop through.
Array keys()
The keys()
method gives you an Array Iterator containing the keys of an array.
Array find()
The find()
method gives back the value of the initial array element that satisfies a specified test function.
This example locates and gives the value of the initial element greater than 18.
Array findIndex()
The findIndex()
function gives the position of the initial array item that meets a specific condition.
This example locates the position of the initial element surpassing the value 18.
New Math Methods
ES6 introduced new functions to the Math object:
Math.trunc()
Math.sign()
Math.cbrt()
Math.log2()
Math.log10()
The Math.trunc() Method
Math.trunc(x)
gives you the whole number part of the value x:
The Math.sign() Method
The Math.sign(x)
function tells us whether x is negative, zero, or positive.
The Math.cbrt() Method
The code Math.cbrt(x)
calculates the cube root of the value x.
The Math.log2() Method
Math.log2(x)
calculates the logarithm of x to the base 2:
The Math.log10() Method
The code Math.log10(x)
calculates the logarithm of x to the base 10.
New Number Properties
ES6 introduced new features to the Number object.
EPSILON
MIN_SAFE_INTEGER
MAX_SAFE_INTEGER
New Number Methods
ES6 introduced two additional methods to the Number object:
Number.isInteger()
Number.isSafeInteger()
The Number.isInteger() Method
The Number.isInteger()
function gives a true
result when the input is a whole number.
The Number.isSafeInteger() Method
A safe integer is a whole number that can be accurately represented as a double precision number.
The Number.isSafeInteger()
function shows true
when the input is a safe whole number.
Safe integers are numbers between -(2^53 - 1) and +(2^53 - 1). For example, 9007199254740991 is a safe integer, but 9007199254740992 is not.
New Global Methods
ES6 introduced two additional global number methods.
The isFinite() Method
The worldwide isFinite()
function gives back false
if the input is Infinity
or NaN
.
Otherwise, it gives back true
:
The isNaN() Method
The worldwide isNaN()
function tells us if a value is NaN
or not. It gives back true
if the input is NaN
, and false
otherwise.
Object entries()
The entries()
function gives you an Array Iterator object containing key/value pairs.
[0, "Banana"]
[1, "Orange"]
[2, "Apple"]
[3, "Mango"]
The entries()
method doesn't modify the original array.
Modules
There are two ways to bring in modules:
Find out more about modules here: JavaScript Modules.
<!DOCTYPE html>
<html>
<body>
<h2>Redeclaring a Variable Using let</h2>
<p id="demo"></p>
<script>
let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Declaring a Variable Using const</h2>
<p id="demo"></p>
<script>
var x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrow Functions</h2>
<p>With arrow functions, you don't need to write "function", "return", or curly brackets.</p>
<p>Arrow functions don't work in Internet Explorer 11 or older versions.</p>
<p id="demo"></p>
<script>
const x = (x, y) => x * y;
document.getElementById("demo").innerHTML = x(5, 5);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrow Functions</h2>
<p>Arrow functions don't function in older versions of Internet Explorer, such as IE11 or earlier.</p>
<p id="demo"></p>
<script>
const x = (x, y) => {
return x * y
};
document.getElementById("demo").innerHTML = x(5, 5);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Operators</h1>
<h2>The ... Operator</h2>
<p>The "spread" operator spreads elements of iterable objects:</p>
<p id="demo"></p>
<script>
const q1 = ["Jan", "Feb", "Mar"];
const q2 = ["Apr", "May", "Jun"];
const q3 = ["Jul", "Aug", "Sep"];
const q4 = ["Oct", "Nov", "May"];
const year = [...q1, ...q2, ...q3, ...q4];
document.getElementById("demo").innerHTML = year;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Operators</h1>
<h2>The ... Operator</h2>
<p>The "Spread" operator helps to add more arguments to function calls by expanding an iterable.</p>
<p id="demo"></p>
<script>
const numbers = [23, 55, 21, 87, 56];
let maxValue = Math.max(...numbers);
document.getElementById("demo").innerHTML = maxValue;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Of Loop</h2>
<p>The "for of" statement goes through all the values of something you can loop through.</p>
<p id="demo"></p>
<script>
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x + " <br> ";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Of Loop</h2>
<p>The "for of" statement goes through all the values of something you can loop through.</p>
<p id="demo"></p>
<script>
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x + " <br> ";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Map Objects</h2>
<p>Creating a Map from an Array:</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
document.getElementById("demo").innerHTML = fruits.get("apples");
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Sets</h2>
<p>Add values to a Set:</p>
<p id="demo"></p>
<script>
// Create a Set
const letters = new Set();
// Add Values to the Set
letters.add("a");
letters.add("b");
letters.add("c");
// Display set.size
document.getElementById("demo").innerHTML = letters.size;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Classes</h1>
<p>Creating two car objects from a car class:</p>
<p id="demo"></p>
<script>
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
document.getElementById("demo").innerHTML = myCar1.name + " " + myCar2.name;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Promise Object</h1>
<h2>The then() Metod</h2>
<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>
<h1 id="demo"></h1>
<script>
const myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() {
myResolve("I love You !!");
}, 3000);
});
myPromise.then(function(value) {
document.getElementById("demo").innerHTML = value;
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Using JavaScript Symbol()</h2>
<p id="demo"></p>
<script>
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
let id = Symbol('id');
person[id] = 140353;
document.getElementById("demo").innerHTML = person[id] + " " + person.id;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>Default Parameter Values</h2>
<p>If y is not passed or undefined, then y = 10:</p>
<p id="demo"></p>
<script>
function myFunction(x, y = 10) {
return x + y;
}
document.getElementById("demo").innerHTML = myFunction(5);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>The Rest Parameter</h2>
<p>The "rest parameter" (...) lets a function handle many arguments like they're in an array.</p>
<p id="demo"></p>
<script>
function sum(...args) {
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
let x = sum(4, 9, 16, 25, 29, 100, 66, 77);
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The includes() Method</h2>
<p>Check if a string includes "world":</p>
<p id="demo"></p>
<p>The includes() method is not supported in Internet Explorer.</p>
<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.includes("world");
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The startsWith() Method</h2>
<p>Check if a string starts with "Hello":</p>
<p id="demo"></p>
<p>The startsWith() method is not supported in Internet Explorer.</p>
<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.startsWith("Hello");
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p>Check if a string ends with "Doe":</p>
<p id="demo"></p>
<p>The endsWith() method is not supported in Internet Explorer.</p>
<script>
let text = "John Doe";
document.getElementById("demo").innerHTML = text.endsWith("Doe");
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The from() Method</h2>
<p>Get an array from any object that has a length property or is iterable.</p>
<p id="demo"></p>
<script>
const myArr = Array.from("ABCDEFG");
document.getElementById("demo").innerHTML = myArr;
</script>
<p>The Array.from() method is not supported in Internet Explorer.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The keys() Method</h2>
<p>Return an Array Iterator object with the keys of the array:</p>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keys = fruits.keys();
let text = "";
for (let x of keys) {
text += x + " <br> ";
}
document.getElementById("demo").innerHTML = text;
</script>
<p>Array.keys() is not supported in Internet Explorer.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The find() Method</h2>
<p id="demo"></p>
<script>
const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);
document.getElementById("demo").innerHTML = "First number over 18 is " + first;
function myFunction(value, index, array) {
return value > 18;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The findIndex() Method</h2>
<p id="demo"></p>
<script>
const numbers = [4, 9, 16, 25, 29];
document.getElementById("demo").innerHTML = "First number over 18 has index " + numbers.findIndex(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.trunc()</h2>
<p>Math.trunc(x) returns the integer part of x:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.trunc(4.7);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.sign()</h2>
<p>Math.sign(x) returns if x is negative, null or positive:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.sign(4);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.cbrt()</h2>
<p>Math.cbrt(x) returns the cube root of x:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.cbrt(8);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.log2()</h2>
<p>Math.log2() returns the base 2 logarithm of a number.</p>
<p>How many times must we multiply 2 to get 8?</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.log2(8);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.log10()</h2>
<p>Math.log10() returns the base 10 logarithm of a number.</p>
<p>How many times must we multiply 10 to get 1000?</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.log10(1000);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Number Object Properties</h2>
<p>EPSILON</p>
<p id="demo"></p>
<script>
let x = Number.EPSILON;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Number Object Properties</h2>
<p>MIN_SAFE_INTEGER</p>
<p id="demo"></p>
<script>
let x = Number.MIN_SAFE_INTEGER;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Number Object Properties</h2>
<p>MAX_SAFE_INTEGER</p>
<p id="demo"></p>
<script>
let x = Number.MAX_SAFE_INTEGER;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Numbers</h1>
<h2>The isInteger() Method</h2>
<p>The isInteger() method returns true if the argument is an integer.</p>
<p>Otherwise it returns false.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Number.isInteger(10) + " <br> " + Number.isInteger(10.5);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Numbers</h1>
<h2>The isSafeInteger() Method</h2>
<p>The isSafeInteger() method returns true if the argument is a safe integer.</p>
<p>Otherwise it returns false.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Number.isSafeInteger(10) + " <br> " + Number.isSafeInteger(12345678901234567890);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Numbers</h1>
<h2>The isFinite() Method</h2>
<p>The isFinite() method returns false if the argument is Infinity or NaN.</p>
<p>Otherwise it returns true.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = isFinite(10 / 0) + " <br> " + isFinite(10 / 1);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Numbers</h1>
<h2>The isNaN() Method</h2>
<p>The isNan() method returns true if the argument is NaN. Otherwise it returns false.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = isNaN("Hello") + " <br> " + isNaN("
10 ");
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The entries() method</h2>
<p>entries() returns an Array Iterator object with key/value pairs:</p>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const f = fruits.entries();
for (let x of f) {
document.getElementById("demo").innerHTML += x + " <br> ";
}
</script>
<p>The entries() method is not supported in Internet Explorer 11 (or earlier).</p>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Modules</h1>
<p id="demo"></p>
<script type="module">
import {
name,
age
} from "./person.js";
let text = "My name is " + name + ", I am " + age + ".";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Modules</h1>
<p id="demo"></p>
<script type="module">
import message from "./message.js";
document.getElementById("demo").innerHTML = message();
</script>
</body>
</html>