Why is my global variable inaccessible inside a function?

I thought myColor would be accessible from the local context sayColor() , but I did not even declare myColor after the first warning. Why?

 var myColor = "blue"; function sayColor() { alert(myColor); //undefined expected blue var myColor = "green"; alert(myColor); //green } sayColor(); 
+4
source share
4 answers

What is going on here is called "rise." Variable declarations that use var and function statements rise above their scope. (Note that from ES6 on let and const have different semantics.) So, for the browser mind, your code looks something like this:

 var myColor = "blue"; function sayColor() { var myColor; alert(myColor); //undefined expected blue myColor = "green"; alert(myColor); //green } sayColor(); 

From MDN :

Each definition of a variable is really a declaration of a variable at the top of its scope and an assignment at the place where that definition is.

+12
source

You are hiding the global variable myColor with a local variable of the same name. Remove the var keyword from the function to see the global variable.

 var myColor = "blue"; function sayColor() { alert(myColor); myColor = "green"; // Omit the "var" keyword. alert(myColor); } sayColor(); 

Javascript has only the scope of the function, and all the variables declared inside the function go up so that they are available throughout the function. The first warning in the original OP version used an uninitialized, raised, local variable, so it printed undefined .

+6
source

You set the variable again inside the function. The browser reads the function before the assignment, and this leads to an undefined result.

Right.

 var myColor = "blue"; function sayColor() { alert(myColor); //undefined expected blue myColor = "green"; alert(myColor); //green } sayColor(); 
+1
source

Because you are announcing it again.

  var myColor = "green"; 

In JavaScript, before the interpreter executes a function, it scans the entire function for var ... statements. This is why your myColor reset variable before the first statement of your function is executed.

+1
source

Source: https://habr.com/ru/post/1489946/