Home  >  Q&A  >  body text

javascript - Question about why the value of i is equal to 5

(function(){
    for(var i = 0; i < 5; i++) {}
    console.log(i) // i = 5
})()

First question: Which part of js knowledge does this belong to?
Second question: Explain in layman’s terms why i is equal to 5?
0o0

欧阳克欧阳克2686 days ago885

reply all(8)I'll reply

  • PHP中文网

    PHP中文网2017-06-12 09:31:37

    Is this problem a closure? I don’t think it is a closure, and there is no nesting of functions. It is a problem of function local variables and anonymous functions.

    Creating an anonymous function and executing it immediately does not involve closures. Just when the loop ends, the value of i becomes 5 and exits the loop, console.log(i)prints the current i, which is 5.

    This is equivalent to:

    var test = function() {
        for(var i = 0; i < 5; i++) {}
        console.log(i) // i = 5
    }
    test();

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-12 09:31:37

    This is not a closure, it’s just a value printed after the for loop speed

    reply
    0
  • 怪我咯

    怪我咯2017-06-12 09:31:37

    This is a problem caused by js not having block-level scope, only function scope. . . Ju can directly pull the closure. . . I accept it. . .

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-06-12 09:31:37

    There is no such thing as block-level scope in JavaScript, so the variables inside the for loop {} and if statement {} can be accessed from the outside.

    Scope is divided into global scope and local scope

    The global scope is built in by the system for you when you create a document.
    Local scope is achieved by creating a function.

    reply
    0
  • 怪我咯

    怪我咯2017-06-12 09:31:37

    • This usually appears in the problem of examining closures

    • i + 1 looped 5 times, so i is 5

    reply
    0
  • ringa_lee

    ringa_lee2017-06-12 09:31:37

    1. You should want to know about closures in js

    2. Because the for loop execution is completed when console.log is executed, i is naturally equal to 5

    reply
    0
  • 怪我咯

    怪我咯2017-06-12 09:31:37

    Let’s take a look at closures combined with timers, or event binding

    reply
    0
  • ringa_lee

    ringa_lee2017-06-12 09:31:37

    Closures in js,

    reply
    0
  • Cancelreply