0

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

1
  • 1
    Because var example = … inside the function does declare a local variable. Omit the var and only do the assignment to the global variable. Commented Mar 14, 2022 at 23:53

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

"initialized the variable twice" - it would be more accurate to say "initialised two different variables"
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.