JS Tutorial
JS Version
JS Objects
JS Function
JS Classes
JS Async
JS HTML DOM
JS Browser BOM
JS Web API
JS AJAX
JS JSON
JS vs JQUERY
JS Graphics
Javascript ES6
ECMAScript 2015 was the second major revision to JavaScript.
ECMAScript 2015 is also called as ES6 and ECMAScript 6.
New Features in ES6
- The let keyword.
- The const keyword.
- Arrow Functions.
- For/of.
- Map Objects.
- Set Objects.
- Classes.
- Promises.
- Symbol.
- Default Parameters.
- Function Rest Parameter.
- String.includes().
- String.startsWith().
- String.endsWith().
- Array.from().
- Array keys().
- Array find().
- Array findIndex().
- New Math Methods.
- New Number Properties.
- New Number Methods.
- New Global Methods.
- Object entries.
- JavaScript Modules.
JavaScript let
The let keyword is used to declare a variable with block scope.
<!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>
Output
Redeclaring a Variable Using let
JavaScript const
The const keyword declares a constant (a JavaScript variable with a constant value).
Constants are much similar to let variables, except that the value cannot be changed.
Example
<!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>
Output
Declaring a Variable Using const
10
Arrow Functions
Arrow functions enables the user to write short syntax for writing function expressions.
The function keyword is not needed, the return keyword, and the curly brackets.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrow Functions</h2>
<p>With arrow functions, you don’t have to type the function keyword, the return keyword, and the curly brackets.</p>
<p>Arrow functions are not supported in IE11 or earlier.</p>
<p id=”demo”></p>
<script>
const x = (x, y) => x * y;
document.getElementById(“demo”).innerHTML = x(5, 5);
</script>
</body>
</html>
Output
With arrow functions, you don't have to type the function keyword, the return keyword, and the curly brackets.
Arrow functions are not supported in IE11 or earlier.
25
Arrow functions do not have their own this. They are not suitable for specifying object methods.
Arrow functions are not hoisted. They need to be defined before they are used.
Using const is safer than using var, as a function expression is always a constant value.
The return keyword can be omitted along with the curly brackets if the function is a single statement. Because of this, it might be a good habit to always keep them:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrow Functions</h2>
<p>Arrow functions are not supported in 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>
Output
JavaScript Arrow Functions
Arrow functions are not supported in IE11 or earlier.
25
The For/Of Loop
The JavaScript for/of statement loops through the values of an iterable objects.
for/of allows you to loop over data structures. which are iterable such as Arrays, Strings, Maps, NodeLists, and more.
The for/of loop consists of the following syntax:
for (variable of iterable) {
// code block to be executed
}
variable – For every iteration the value of the next property is assigned to the variable. Variable can be declared with const, let, or var.
iterable – An object that has iterable properties.
Looping over an Array
Object Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Of Loop</h2>
<p>The for of statement loops through the values of any iterable object:</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>
Output
JavaScript For Of Loop
The for of statement loops through the values of any iterable object:
BMWVolvo
Mini
Looping over a String
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Of Loop</h2>
<p>The for of statement loops through the values of an iterable object.</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>
Output
JavaScript For Of Loop
The for of statement loops through the values of an iterable object.
Ja
v
a
s
c
r
i
p
t
JavaScript Maps
Using an Object as a key is an important Map feature.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Map Objects</h2>
<p>Objects as keys in a Map:</p>
<p id=”demo”></p>
<script>
// Create Objects
const apples = {name: ‘Apples’};
const bananas = {name: ‘Bananas’};
const oranges = {name: ‘Oranges’};
// Create a new Map
const fruits = new Map();
// Add the Objects to the Map
fruits.set(apples, 500);
fruits.set(bananas, 300);
fruits.set(oranges, 200);
// Display Object Type
document.getElementById(“demo”).innerHTML = fruits;
</script>
</body>
</html>
Output
JavaScript Map Objects
Objects as keys in a Map:
[object Map]
JavaScript Sets
Example
<!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>
Output
JavaScript Sets
Add values to a Set:
3
JavaScript Classes
JavaScript Classes are templates for JavaScript Objects.
Using the keyword class to create a class.
Always adding a method named constructor():
Syntax
class ClassName {
constructor() { … }
}
Example
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
The example above creates a class named “Car”.
The class consists of two initial properties: “name” and “year”.
A JavaScript class is not an object.
It is a template for JavaScript objects.
Using a Class
When you have a class, it can be used to create objects:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Class</h2>
<p>How to use a JavaScript Class.</p>
<p id=”demo”></p>
<script>
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
const myCar = new Car(“Ford”, 2014);
document.getElementById(“demo”).innerHTML =
myCar.name + ” ” + myCar.year;
</script>
</body>
</html>
Output
JavaScript Class
How to use a JavaScript Class.
Ford 2014
JavaScript Promises
A Promise is a JavaScript object that is used to links “Producing Code” and “Consuming Code”.
“Producing Code” can take some time and “Consuming Code” must wait for the result.
Promise Syntax
const myPromise = new Promise(function(myResolve, myReject) {
// “Producing Code” (May take some time)
myResolve(); // when successful
myReject(); // when error
});
// “Consuming Code” (Must wait for a fulfilled Promise).
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
Array reduce()
This example finds the sum of all numbers in an array:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Promise</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>
Output
JavaScript Promise
Wait 3 seconds (3000 milliseconds) for this page to change.
The Symbol Type
A JavaScript Symbol is a primitive datatype similar tpo Number, String, or Boolean.
It represents a unique “hidden” identifier that cannot be accessed by any code.
For instance, if different coders want to add a person.id property to a person object belonging to a third-party code, they could mix each others values.
Using Symbol() to create a unique identifiers, solves this problem:
Example
<!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>
Output
Using JavaScript Symbol()
140353 undefined
Default Parameter Values
ES6 enables function parameters to have default values.
Example
<!DOCTYPE html>
<html>
<body>
<h2>Default Parameter Values</h2>
<p id=”demo”></p>
<script>
function myFunction(x, y = 10) {
// y is 10 if not passed or undefined
return x + y;
}
document.getElementById(“demo”).innerHTML = myFunction(5);
</script>
</body>
</html>
Output
Default Parameter Values
15
Function Rest Parameter
The rest parameter (…) enables a function to treat an indefinite number of arguments as an array:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Function Rest Parameter</h2>
<p>The rest parameter (…) allows a function to treat an indefinite number of arguments as 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>
Output
JavaScript Function Rest Parameter
The rest parameter (...) allows a function to treat an indefinite number of arguments as an array:
326
String.includes()
The includes() method is used to returns true if a string contains a specified value, otherwise false:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Search</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>
Output
JavaScript String Search
Check if a string includes "world":
true
The includes() method is not supported in Internet Explorer.
String.startsWith()
The startsWith() method is used to return a true if a string begins with a specified value, otherwise false:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</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>
Output
JavaScript Strings
Check if a string starts with "Hello":
true
The startsWith() method is not supported in Internet Explorer.
String.endsWith()
The endsWith() method is used to return a true if a string ends with a specified value, otherwise false:
<!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>
Output
JavaScript Strings
Check if a string ends with "Doe":
true
The endsWith() method is not supported in Internet Explorer.
Array.from()
The Array.from() method is used to return an Array object from any object with a length property or any iterable object.
Example
Creating an Array from a String:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>The Array.from() method returns an Array object from any object with a length property or any iterable object.</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>
Output
JavaScript Arrays
The Array.from() method returns an Array object from any object with a length property or any iterable object.
A,B,C,D,E,F,G
Array keys()
The keys() method is used to return an Array Iterator object with the keys of an array.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>The Array.keys() method returns 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>
Output
JavaScript Arrays
The Array.keys() method returns an Array Iterator object with the keys of the array.
01
2
3
Array find()
The find() method is used to return the value of the first array element that passes a test function.
This example searches (returns the value of ) the first element that is larger than 18:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.find()</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>
Output
JavaScript Array.find()
First number over 18 is 25
Array findIndex()
The findIndex() method is used to return the index of the first array element that passes a test function.
This example searches the index of the first element that is larger than 18:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.findIndex()</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>
Output
JavaScript Array.findIndex()
First number over 18 has index 3
New Math Methods
ES6 added the following methods to the Math object:
- trunc()
- sign()
- cbrt()
- log2()
- log10()
The Math.trunc() Method
Math.trunc(x) is used to returns the integer part of x:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Getters and Setters</h2>
<p>Getters and setters allow you to get and set properties via methods.</p>
<p>This example creates a getter for a property called fullName.</p>
<p id=”demo”></p>
<script>
// Create an object:
var person = {
firstName: “John”,
lastName : “Doe”,
get fullName() {
return this.firstName + ” ” + this.lastName;
}
};
// Display data from the object using a getter:
document.getElementById(“demo”).innerHTML = person.fullName;
</script>
</body>
</html>
Output
JavaScript Getters and Setters
Getters and setters allow you to get and set properties via methods.
This example creates a getter for a property called fullName.
John Doe
The Math.sign() Method
Math.sign(x) is used to returns if x is negative, null or positive:
Example
<!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>
Output
JavaScript Math.sign()
Math.sign(x) returns if x is negative, null or positive:
1
The Math.cbrt() Method
Math.cbrt(x) is used to return the cube root of x:
Example
<!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>
Output
JavaScript Math.cbrt()
Math.cbrt(x) returns the cube root of x:
2
The Math.log2() Method
Math.log2(x) returns the base 2 logarithm of x:
Example
<!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>
Output
JavaScript Math.log2()
Math.log2() returns the base 2 logarithm of a number.
How many times must we multiply 2 to get 8?
3
The Math.log10() Method
Math.log10(x) returns the base 10 logarithm of x:
Example
<!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>
Output
JavaScript Math.log10()
Math.log10() returns the base 10 logarithm of a number.
How many times must we multiply 10 to get 1000?
3
New Number Properties
ES6 added the following properties to the Number object:
- EPSILON
- MIN_SAFE_INTEGER
- MAX_SAFE_INTEGER
EPSILON
Example
<!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>
Output
Number Object Properties
EPSILON
2.220446049250313e-16
MIN_SAFE_INTEGER
Example
<!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>
Output
Number Object Properties
MIN_SAFE_INTEGER
-9007199254740991
MAX_SAFE_INTEGER
Example
<!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>
Output
Number Object Properties
MAX_SAFE_INTEGER
9007199254740991
ES6 added 2 new methods to the Number object:
- isInteger()
isSafeInteger()
The Number.isInteger() Method
The Number.isInteger() method is used to return true if the argument is an integer.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Number Methods</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>
Output
JavaScript Number Methods
The isInteger() method returns true if the argument is an integer.
Otherwise it returns false.
truefalse
The Number.isSafeInteger() Method
A safe integer can be defined as an integer that can be represented as a double precision number.
The Number.isSafeInteger() method is used to returns true if the argument is a safe integer.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Number Methods</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>
Output
JavaScript Number Methods
The isSafeInteger() method returns true if the argument is a safe integer.
Otherwise it returns false.
truefalse
New Global Methods
ES6 added 2 new global number methods:
- isFinite()
- isNaN()
The isFinite() Method
The global isFinite() method is used to return false if the argument is Infinity or NaN.
Otherwise it returns true:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Number Methods</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>
Output
JavaScript Number Methods
The isFinite() method returns false if the argument is Infinity or NaN.
Otherwise it returns true.
falsetrue
The isNaN() Method
The global isNaN() method is used to return true if the argument is NaN. Otherwise ,it returns false:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Number Methods</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>
Output
JavaScript Number Methods
The isNan() method returns true if the argument is NaN. Otherwise it returns false.
truefalse
Object entries()
Example
Creating an Array Iterator, and then iterate over the key/value pairs
<html>
<body>
<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>
Output
The entries() method
entries() returns an Array Iterator object with key/value pairs:
0,Banana1,Orange
2,Apple
3,Mango
The entries() method returns an Array Iterator object with key/value pairs:
[0, “Banana”]
[1, “Orange”]
[2, “Apple”]
[3, “Mango”]
The entries() method does not change the original array.
Modules
Modules are imported in two differen ways:
Import from named exports
Import named exports from the file person.js:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Modules</h2>
<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>
Output
JavaScript Modules
My name is Jesse, I am 40.
Import from default exports
Import a default export from the file message.js:
Example
<!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>
Output
JavaScript Modules
Jesse is 40 years old.