The JavaScript for…of statement iterates over the values of iterable objects.
It allows you to loop through data structures that are iterable, such as Arrays, Strings, Maps, NodeLists, and others.
The syntax for the for…of loop is as follows:
for (variable of iterable) { // code block to be executed } |
Variable: In each iteration, the value of the next property is assigned to the variable. The variable can be declared using const, let, or var.
Iterable: An object that contains iterable properties.
const cars = [“BMW”, “Volvo”, “Mini”]; let text = “”; for (let x of cars) { text += x + ” “; } |
let language = “JavaScript”; let text = “”; for (let x of language) { text += x + ” “; } |
const fruits = new Map([ [“apples”, 500], [“bananas”, 300], [“oranges”, 200] ]); |
// Create a Set const letters = new Set(); // Add some values to the Set letters.add(“a”); letters.add(“b”); letters.add(“c”); |
JavaScript classes serve as blueprints for creating JavaScript objects.
Use the class
keyword to define a class.
Always include a method called constructor()
to initialize the object.
class ClassName { constructor() { ... } } |
class Car { constructor(name, year) { this.name = name; this.year = year; } } |
The example above defines a class called “Car,” which has two initial properties: name and year.
Once you have a class, you can use it to create objects.
const myCar1 = new Car(“Ford”, 2014); const myCar2 = new Car(“Audi”, 2019); |
A Promise is a JavaScript object that connects “Producing Code” and “Consuming Code.”
The “Producing Code” may take some time to execute, and the “Consuming Code” must wait for the result.
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 */ } ); |
const myPromise = new Promise(function(myResolve, myReject) { setTimeout(function() { myResolve(“I love You !!”); }, 3000); }); myPromise.then(function(value) { document.getElementById(“demo”).innerHTML = value; }); |