Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

javascript - Will I have any problems if I declare the same variable multiple times?

So lets say I have some code:

//Javascript
var elements = [];
function addNumbah1(){
    var i = 1;
    elements.push(i);
}
function addNumbah2(){
    var i = 2;
    elements.push(i);
}

And that goes on up to addNumbah999(), is it bad form to declare the i variable every time? Will that break anything? Should I do:

//Javascript
var elements = [];
var i
function addNumbah1(){
    i = 1;
    elements.push(i);
}
function addNumbah2(){
    i = 2;
    elements.push(i);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Short answer: NO, JS hoists all variable declarations to the top of the scope, regardless of how many times you've declared them:

var i = 0
for (var i=0;i<10;i++)
{
    var j = i%2;//declared 10 times, on each iteration
}

Will be translated to

var i, j; //i is undefined at this point in the code.
for (i = 0;i<10;i++)
{
    j = i%2;//declared 10 times, on each iteration
}

In your first example, you're declaring i as a variable in a function's scope, which is what you must do to avoid cluttering the global scope. The memory these variables use is allocated when the function is called, and deallocated when the function returns (roughly, closures form an exception, but that would take us to far). Consider this:

var i = 10;
function someF()
{
    var i = 1;
    alert(i);
}
someF();//alerts 1 <-- value of i, local to someF
alert(i);//10, global i is unchanged

But if you were to omit the var:

function someF()
{
    i = 1;
    alert(i);
}

You'll see that 1 is alerted twice. If JS can't find a variable declaration in the current scope, it will look in the higher scopes until a var is found. If no variable is found, JS will create one for you in the highest scope (global). Check my answer here on how implied globals work for a more detailed example, or read the MDN pages, especially the section on Name conflicts

Lastly, I'd like to add that globals, especially implied globals, are evil. Also know that the ECMA6 standard is clearly moving away from global variables and introduces support for true block-scopes. As you can see here
Oh, and if you want to check if a function uses implied globals: 'use strict'; is a great thing:

(function()
{
    'use strict';
    var localVar = 123;//ok
    impliedGlobal = 123;//TypeError!
}());

As you can see, implied globals are not allowed. See MDN on strict mode for the full explanation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...