Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

can anyone please tell me why given below 's snippet output is coming undefined?, was expecting test

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()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading