Solution to the problem of var in for loop

Solution to the problem of var in for loop

Preface

var is a way to declare variables in ES5. I have always heard that when declaring variables with var, there is a problem of loop variables leaking to global variables, but I always can't figure out the impact of this "global". In addition, it is not clear when the output result is an increasing/decreasing value and when the output is the same value.

Problem reproduction

for (var i = 1; i <= 5; i++) {
  setTimeout(function timer() {
    console.log(i)
  }, i * 1000)
}

Expected result: 12345

Print result: 66666

Solution

Closures

for (var i = 1; i <= 5; i++) {
    (function (j) {
        setTimeout(function timer() {
            console.log(j)
        }, j * 1000)
    })(i)
}

setTimeout third parameter

for (var i = 1; i <= 5; i++) {
   setTimeout(
       function timer(j) {
           console.log(j)
       },
       i * 1000,
       i
   )
}

Use let to define i

for (let i = 1; i <= 5; i++) {
    setTimeout(function timer() {
        console.log(i)
    }, i * 1000)
}

let

Regarding let, remember: the current i is only valid in this loop, and i in each loop is actually a new variable.

The JavaScript engine will remember the value of the previous loop internally, and when initializing the variable i of this loop, it will perform calculations based on the previous loop.

In addition, the for loop has another special feature, that is, the part that sets the loop variable is a parent scope, and the loop body is a separate child scope.

for (let i = 0; i < 3; i++) {
let i = 'abc';
console.log(i);
}
//abc
//abc
//abc

Summarize

This is the end of this article about how to solve the problems encountered when using var for loop. For more information about var for loop problems, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • js for loop, why must we add var to define i variable
  • The difference between var and let in jQuery for loop
  • Detailed explanation of the difference between let and var in es6 for loop

<<:  Explore the truth behind the reload process in Nginx

>>:  Detailed explanation of the code for querying data of a certain day, month, or year in MySQL

Recommend

CentOS 8 officially released based on Red Hat Enterprise Linux 8

The CentOS Project, a 100% compatible rebuild of ...

Whitespace processing in HTML/CSS and how to preserve whitespace in the page

Whitespace rules in HTML In HTML, multiple spaces...

Web project development VUE mixing and inheritance principle

Table of contents Mixin Mixin Note (duplicate nam...

Copy fields between different tables in MySQL

Sometimes, we need to copy a whole column of data...

JS implementation of carousel carousel case

This article example shares the specific code of ...

Mini Programs enable product attribute selection or specification selection

This article shares the specific code for impleme...

Detailed explanation of the simple use of MySQL query cache

Table of contents 1. Implementation process of qu...

How to implement an array lazy evaluation library in JavaScript

Table of contents Overview How to achieve it Spec...

Solution to the problem that Java cannot connect to MySQL 8.0

This article shares a collection of Java problems...

Application and implementation of data cache mechanism for small programs

Mini Program Data Cache Related Knowledge Data ca...

Vue Basics Listener Detailed Explanation

Table of contents What is a listener in vue Usage...

Introduction to who command examples in Linux

About who Displays users logged into the system. ...

Introduction to commonly used MySQL commands in Linux environment

Enter the mysql command: mysql -u+(user name) -p+...

Five ways to traverse JavaScript arrays

Table of contents 1. for loop: basic and simple 2...