Detailed discussion of the differences between loops in JavaScript

Detailed discussion of the differences between loops in JavaScript

Preface

When using loops in JavaScript, there are two key things that need to be defined correctly: enumerable properties and iterable objects.

Enumerable properties

One of the defining characteristics of an enumerable object is that when we assign a property to an object via the assignment operator, we set the internal enumerable flag (enumerable) to true. This is the default value.

However, we can change this behavior by setting it to false.

The rule of thumb is that enumerable properties always appear in a for...in loop.

Let's look at this:

const users = {}
users.languages ​​= 'JavaScript'
​
Object.getOwnPropertyDescriptor(users, 'languages')
// output -> { value: 'JavaScript', writable: true, enumerable: true, configurable: true }
​
// Have more control over the properties we use in the loop Object.defineProperty(users, 'role', { value: 'Admin', writable: true, enumerable: false })
​
for (const item in users) {
  console.log(item) // languages
}

As you can see, we added a languages ​​property to the users variable and used the Object.getOwnPropertyDescriptor method to output the enumerable property of the languages ​​property descriptor as true.

Use Object.defineProperty to add the role attribute and set enumerable to false. The role attribute is not output in the for...in loop. That is, the properties in the for...in loop are enumerable properties.

Iterable objects

An object is iterable if it defines its iteration behavior. In this case, the value being looped over in the for...of construct defines its iteration behavior. Iterable built-in types include Array, String, Set, and Map objects are not iterable because they do not specify an @iterator method.

Basically, in JavaScript, all iterable objects are enumerable objects, but not all enumerable objects are iterable objects.

Here's one way to conceptualize it: for...in finds objects in the data, while for...of finds repeated sequences.

Let's see how this all works when used with the Array data type:

const languages ​​= ['JavaScript', 'Python', 'Go']
​
// Use with for...in loop for (const language in languages) {
  console.log(language)
}
// output
// 0
// 1
// 2
​
// Use with for...of loop for (const language of languages) {
  console.log(author)
}
// output -> JavaScript Python Go

One thing to keep in mind when using this construct is that if typeof is called and the output is object, you can use a for...in loop.

Let's look at this operation on the languages ​​variable:

typeof languages ​​// "object" -> so we can use for in

This may seem surprising at first, but it’s important to note that arrays are a special type of object that are keyed by indices. Knowing that for...in will look for objects in a construct can help us greatly. When the for...in loop finds an object, it loops over each key.

We can visualize the way the for ..in loop works on the languages ​​array as follows:

const languages ​​= {
  0: 'JavaScript',
  1: 'Python',
  2: 'Go'
}

Note: for...in will iterate over the keys in no particular order if it can be tracked down to an object (or inherits from an object prototype chain).

Also, if it implements an iterator for.. of construct, it will loop over the value on each iteration.

In forEach and map methods

Although the forEach and map methods can be used to achieve the same goal, their behavior and performance characteristics differ.

At a basic level, when functions are called, they receive a callback as an argument.

Consider the following snippet:

const scoresEach = [2, 4 ,8, 16, 32]
const scoresMap = [2, 4 ,8, 16, 32]
const square = (num) => num * num

Let’s take a closer look at some of the differences in their operations.

forEach returns undefined, while map returns a new array:

let newScores = []
const resultWithEach = scoresEach.forEach(score => {
  const newScore = square(score)
  newScores.push(newScore)
})
​
const resultWithMap = scoresMap.map(square)
​
console.log(resultWithEach) // undefined
console.log(resultWithMap) // [4, 16, 64, 256, 1024]

Map is a pure function, while forEach performs some mutations:

console.log(newScores) // [4, 16, 64, 256, 1024]

In my opinion, map supports the functional programming paradigm. We don't have to always perform mutations to get the desired result, unlike forEach where we had to mutate the newScores variable. On each run, when provided with the same input, the map function will produce the same results. Meanwhile, the forEach counterpart will be pulled from the previous value from the last mutation.

Chain calls

Map can be used to chain calls because the returned result is an array. Therefore, any other array method can be called immediately on the result. In other words, we can call methods like filter, reduce, some, etc. This is not possible with forEach because the return value is undefined.

performance

The map method often performs better than the forEach method.

Check the performance of an equivalent block of code implemented using map and forEach. On average, you will see map functions execute at least 50% faster.

in conclusion

Of all the looping constructs discussed above, the one that gives us the most control is the for..of loop. We can use it with the keywords return, continue, and break. This means we can specify what should happen to each element in the array and whether to leave early or skip it.

This concludes this article on the differences between loops in JavaScript. For more information on the differences between JavaScript loops, please search 123WORDPRESS.COM’s previous articles or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Do you know all 24 methods of JavaScript loop traversal?
  • JavaScript event loop case study
  • Summary of the use of three for loop statements in JavaScript (for, for...in, for...of)
  • Analysis of the event loop mechanism of js
  • How many common loops do you know about array traversal in JS?
  • Detailed explanation of various loop speed tests in JS that you don’t know
  • JavaScript implements circular carousel
  • Detailed explanation of loop usage in javascript examples

<<:  A simple and effective solution to forget the initial password when installing MySQL

>>:  Detailed explanation of the principles and usage of MySQL master-slave replication and read-write separation

Recommend

W3C Tutorial (4): W3C XHTML Activities

HTML is a hybrid language used for publishing on ...

Four ways to modify the default CSS style of element-ui components in Vue

Table of contents Preface 1. Use global unified o...

CSS3 analysis of the steps for making Douyin LOGO

"Tik Tok" is also very popular and is s...

Implementation of Vue counter

Table of contents 1. Implementation of counter 2....

MySQL 8.0.19 installation and configuration tutorial under Windows 10

I will be learning MySQL next semester. I didn...

Understand all aspects of HTTP Headers with pictures and text

What are HTTP Headers HTTP is an abbreviation of ...

Detailed process of installing and deploying onlyoffice in docker

0. System requirements CPU I5-10400F or above Mem...

Basic knowledge of MySQL learning notes

View Database show databases; Create a database c...

How to use provide to implement state management in Vue3

Table of contents Preface How to implement Vuex f...

React+Amap obtains latitude and longitude in real time and locates the address

Table of contents 1. Initialize the map 2. Map Po...

Font references and transition effects outside the system

Copy code The code is as follows: <span style=...

How to set default value for datetime type in MySQL

I encountered a problem when modifying the defaul...

7 interesting ways to achieve hidden elements in CSS

Preface The similarities and differences between ...