The let keyword allows you to declare a variable with block scope.
var x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
The const keyword allows you to declare a constant (a JavaScript variable with a constant value).
Constants are similar to let variables, except that the value cannot be changed.
var x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
Arrow functions allows a short syntax for writing function expressions. You don't need the function keyword, the return keyword, and the curly brackets.
// ES5
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y;
Arrow functions do not have their own this. They are not well suited for defining object methods.
Arrow functions are not hoisted. They must be defined before they are used.
Using const is safer than using var, because a function expression is always a constant value.
You can only omit the return keyword and the curly brackets if the function is a single statement. Because of this, it might be a good habit to always keep them:
const x = (x, y) => { return x * y };
The ... operator expands an iterable (like an array) into more elements:
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];
The ... operator can be used to expand an iterable into more arguments for function calls:
const numbers = [23,55,21,87,56];
let maxValue = Math.max(...numbers);
The JavaScript for/of statement loops through the values of an iterable objects.
for/of lets you loop over data structures that are iterable such as Arrays, Strings, Maps, NodeLists, and more.
The for/of loop has 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
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x + " ";
}
Looping over a String
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x + " ";
}
Being able to use an Object as a key is an important Map feature.
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
JavaScript Classes are templates for JavaScript Objects.
Use the keyword class to create a class.
Always add a method named constructor():
class ClassName {
constructor() { ... }
}
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
The example above creates a class named "Car". The class has two initial properties: "name" and "year".
A JavaScript class is not an object.
It is a template for JavaScript objects.