Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

314
Views
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()
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!