Declaring a Javascript variable twice in same scope - Is it an issue?

前端 未结 3 769
甜味超标
甜味超标 2020-12-14 14:59

Would the following code cause any issues?:

var a = 1;
var a = 2;

My understanding is that javascript variables are declared at the start o

3条回答
  •  悲哀的现实
    2020-12-14 15:48

    Such a duplicate variable declaration will not cause any problems thanks to javascript's variable hoisting feature. so in your DOM wherever you have declared variables but assigned (or) not assigned, they will be placed at the top during compilation.

    Example:
        var foo='hai!';
        bar='welcome!';
        var bar;
    

    You may expect above code snippet should throw "unidentified" error but still javascript manages it by placing the bar variable's declaration at the top. So even before variable declaration its value can be assigned as opposed to other languages.

    Hope this helps you to some extent

提交回复
热议问题