Redeclaring a javascript variable

后端 未结 8 1777
耶瑟儿~
耶瑟儿~ 2020-11-29 05:33

In this tutorial there is written:

If you redeclare a JavaScript variable, it will not lose its value.

Why should I redeclare a variable? Is it

8条回答
  •  爱一瞬间的悲伤
    2020-11-29 06:17

    It doesn't lose it's value because of Hoisting

    var x = 5;
    var x;
    
    // this is same as
    
    var x; // undefined;
    x = 5;
    

    So when you say "If you redeclare a JavaScript variable, it will not lose its value."

    As per hoisting, the declaration(s), all of them , move to the top. And then the variable is assigned.

    var x = 25;
    var x; // redeclare first time
    var x; // redeclare second time
    
    // is same as 
    
    var x; // undefined
    var x; // Not sure if this happens, but doesn't make a difference, it's still undefined
    x = 25;
    

    As for practicality, it happens sometimes. Look at @steveoliver 's answer.

提交回复
热议问题