0

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()
Docu Care
  • 3
  • 3
  • `var name` inside the function makes `name` a local variable for the whole function, shadowing the global variable `name`. The variable starts off `undefined` until it is defined (`name = "test 2"` is not hoisted). – Amadan Jun 06 '22 at 07:44

1 Answers1

-1

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
Ian
  • 1,198
  • 1
  • 5
  • 15