What is the for… Of circulation

for… The of statement creates a loop to iterate over an iterable object. For… introduced in ES6. Of cycle instead of for… In and forEach(), and support the new iteration protocol. for… Of allows you to iterate over iterable data structures like Arrays, Strings, Maps, Sets, etc.

grammar

for (variable of iterable) {
    statement
}
Copy the code
  • Variable: The attribute value of each iteration is assigned to the variable.
  • Iterable: An object with enumerable properties that can be iterated over.

Use cases

Let’s look at some use cases.

The Arrays (array)

Arrays are list-like objects. Array prototypes have various methods that allow you to manipulate them, such as modifying and traversing. The following for hand on an array… Of operation:

// array-example.js
const iterable = ['mini', 'mani', 'mo'];
 
for (const value of iterable) {
  console.log(value);
}
 
// Output:
// mini
// mani
// mo
Copy the code

The result is to print out every value in the Iterable array.

Maps (map)

A Map object holds key-value pairs. Objects and raw values can be used as keys or values. Map objects iterate over elements based on how they are inserted. In other words, for… The of loop returns an array of key-values for each iteration.

// map-example.js
const iterable = new Map([['one', 1], ['two', 2]]);
 
for (const [key, value] of iterable) {
  console.log(`Key: ${key} and Value: ${value}`);
}
 
// Output:
// Key: one and Value: 1
// Key: two and Value: 2
Copy the code

Set (Set)

Set objects allow you to store unique values of any type, which can be primitive values or objects. A Set object is just a collection of values. Set elements are iterated over based on their insertion order. A value in a Set can occur only once. If you create a Set with multiple identical elements, it is still considered a single element.

// set-example.js
const iterable = new Set([1, 1, 2, 2, 1]);
 
for (const value of iterable) {
  console.log(value);
}
// Output:
// 1
// 2
Copy the code

Even though our Set has multiple ones and twos, it outputs only ones and twos.

String(String)

Strings are used to store data as text.

// string-example.js
const iterable = 'javascript';
 
for (const value of iterable) {
  console.log(value);
}
 
// Output:
// "j"
// "a"
// "v"
// "a"
// "s"
// "c"
// "r"
// "i"
// "p"
// "t"
Copy the code

Here, you iterate over the string and print out the characters on each index.

Arguments Object

Think of a parameter object as an array-like object corresponding to the parameters passed to the function. Here’s a use case:

// arguments-example.js
function args() {
  for (const arg of arguments) {
    console.log(arg);
  }
}
 
args('a', 'b', 'c');
// Output:
// a
// b
// c
Copy the code

You might be thinking, what’s going on? ! As mentioned earlier, arguments receive any arguments passed to the args() function when a function is called. So, if we pass 20 arguments to the args() function, we will print out 20 arguments.

Generators(Generators)

A generator is a function that can exit a function and re-enter it later.

// generator-example.js
function* generator(){ 
  yield 1; 
  yield 2; 
  yield 3; 
}; 
 
for (const g of generator()) { 
  console.log(g); 
}
 
// Output:
// 1
// 2
// 3
Copy the code

Function * defines a Generator function that returns a Generator object. More information about generators.

Exit the iteration

JavaScript provides four known methods for terminating loop execution: break, continue, return, and throw. Let’s look at an example:

const iterable = ['mini', 'mani', 'mo'];
 
for (const value of iterable) {
  console.log(value);
  break;
}
 
// Output:
// mini
Copy the code

In this example, we use the break keyword to terminate the loop after one execution, so only mini is printed.

Ordinary objects cannot be iterated

for… The of loop is only suitable for iteration. Ordinary objects are not iterable. Let’s take a look:

const obj = { fname: 'foo', lname: 'bar' };
 
for (const value of obj) { // TypeError: obj[Symbol.iterator] is not a function
    console.log(value);
}
Copy the code

Here, we define a plain object obj, and when we try for… TypeError: obj[Symbol. Iterator] is not a function TypeError: obj[Symbol. Iterator] is not a function.

We can get around this by converting array-like objects into arrays. The object will have a Length attribute, and its elements must be indexable. Let’s look at an example:

// object-example.js
const obj = { length: 3, 0: 'foo', 1: 'bar', 2: 'baz' };
 
const array = Array.from(obj);
for (const value of array) { 
    console.log(value);
}
// Output:
// foo
// bar
// baz
Copy the code

The array.from () method lets me create a new instance of Array from array-like or iterable objects.

The For… Of vs For… in

for… The IN loop iterates through all the enumerable properties of the object.

//for-in-example.js
Array.prototype.newArr = () => {};
Array.prototype.anotherNewArr = () => {};
const array = ['foo', 'bar', 'baz'];
 
for (const value in array) { 
  console.log(value);
}
// Outcome:
// 0
// 1
// 2
// newArr
// anotherNewArr
Copy the code

for… In not only enumerates the array declaration above, it also looks for inherited non-enumeration properties from the constructor’s prototype, in this case newArr and anotherNewArr are also printed out.

for… Of is more specific to collections (such as groups of numbers and objects), but not to all objects.

Note: Any element that has the Symbol. Iterator attribute is iterable.

Array.prototype.newArr = () => {};
const array = ['foo', 'bar', 'baz'];
 
for (const value of array) { 
  console.log(value);
}
// Outcome:
// foo
// bar
// baz
Copy the code

for… In does not consider the non-enumerable properties of the constructor stereotype. It just looks for the enumerable property and prints it out.

summary

Understand the for… The use of the OF loop can save a lot of time during development. Hopefully this article has helped you understand and write better loop structures in JavaScript development. Make you happy coding!