Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

The For/Of Loop

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.

Looping over an Array

Example

const cars = [“BMW”“Volvo”“Mini”];
let text = “”;

for (let x of cars) {
  text += x + ” “;
}

Looping over a String

Example

let language = “JavaScript”;
let text = “”;

for (let x of language) {
    text += x + ” “;
}

JavaScript Maps

Example

const fruits = new Map([
[“apples”500],
[“bananas”300],
[“oranges”200]
]);

JavaScript Sets

Example

// Create a Set
const letters = new Set();

// Add some values to the Set
letters.add(“a”);
letters.add(“b”);
letters.add(“c”);

JavaScript Classes

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.

Syntax

class ClassName {
  constructor() { ... }
}

Example

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.

Using a Class

Once you have a class, you can use it to create objects.

Example

const myCar1 = new Car(“Ford”2014);
const myCar2 = new Car(“Audi”2019);

JavaScript Promises

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.

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 */ }
);

Example Using a Promise

const myPromise = new Promise(function(myResolve, myReject) {
  setTimeout(function() { myResolve(“I love You !!”); }, 3000);
});

myPromise.then(function(value) {
  document.getElementById(“demo”).innerHTML = value;
});