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

158
Views
Global scope, variable outside function Javascript

I have declared var example at the beginning (it should be in global scope, or?!). Why it is undefined after calling the function?

var example;
  
  function test(){
    var x = 2;
    var y = 5;
    var example = x + y;
    console.log(example);  // 7: works OK after calling the function    
  };

  test();
  console.log(example); // undefined ?!

Edit: Hello, Thanks for your answers, I´ve found an article about this - Variable Shadowing

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The reason is you have initialized the variable twice. First Initialization outside the function block which is globally available, Second within the function block which is specifically available to the function block.

Your Second Initialization will override the first within the function. After execution of the function, the second example variable will no longer be available and it will be referencing the globally declared first example variable.

var example;
  
  function test(){
    var x = 2;
    var y = 5;
    example = x + y;
    console.log(example);  //Prints the value     
  };

  test();
  console.log(example); // Prints the value
about 4 years ago · Juan Pablo Isaza Report

0

the first console.log(example) is running the example inside the function block, so it will print the value of the command you gave.

the second console.log(example) is running the example you declare in first line which is doesn't has value, so it will print undefined.

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!