Given below is the snippet that did not get why undefined output is coming, please elaborate Thanks in advance.
var name = "test";
function message() {
console.log(name);
var name = "test 2";
}
message()
Given below is the snippet that did not get why undefined output is coming, please elaborate Thanks in advance.
var name = "test";
function message() {
console.log(name);
var name = "test 2";
}
message()
That's because you declared a local variable with the same name, and it masks the global variable.
So when you write name
you refer to the local variable.
That's true even if you write it before the declaration of that local variable, variables in JavaScript are function-scoped.
However, you can use the fact that global variables are properties of the global object (window
):
var name = "test";
function message1() {
console.log(name);
var name = "test 2";
}
function message2() {
console.log(name);
}
function message3() {
console.log(name);
name = "test 2";
}
function message4() {
console.log(name);
var name = window.name || "";
}
function message5() {
var name = window.name || "";
console.log(name);
}
message1(); // undefined
message2(); // test
message3(); // test
message4(); // undefined
message5(); // test 2