Why add a "var" in front of an existing variable?


#1



In the first chapter of "introduction to 'while' loop in JS" section, I get puzzled by the following sample code. Why is there another "var" in front of the "coinFace" variable in the while loop? I remember that if we want to change the value of an existing variable, we don't have to add another "var" in front of that variable since it's already created.


var coinFace = Math.floor(Math.random() * 2);

while(coinFace === 0){
	console.log("Heads! Flipping again...");
	var coinFace = Math.floor(Math.random() * 2);
}
console.log("Tails! Done flipping.");


#2

Variables are global unless said to be otherwise, var confines them to the enclosing function (or global if outside function) and let (ES6) confines them to the enclosing block, statement, or expression

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

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

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

The tighter the better, if for no other reason than to broadcast your intentions


#3

Thanks for your answer. But I am still a bit confused. I understand the concepts of global and local variable, but it seems that the question I have with the sample code doesn't relate to these two concepts because there are actually no functions in the sample code. That is to say, since "coinFace" is and has always been a global variable in the sample code, why is there another "var" in front of it when its value is changed ?


#4

Now you kind of added enough assumptions into your question to rule out all answers.
With no enclosing function, var has no additional effect.


#5

Oh, I see what you mean. The purpose of adding "var" is actually to confine variables to the enclosing block and it has no additional effect if there is no enclosing function. Thanks a lot!!


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.