Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my global variable is not accessible within a function? [duplicate]

Tags:

javascript

I thought that myColor would be accessible from sayColor() local context but it isn't even though I'm declaring myColor after the first alert. Why?

var myColor = "blue";
function sayColor() {
    alert(myColor); //undefined expected blue
    var myColor = "green";
    alert(myColor); //green
}
sayColor();
like image 884
Alfredo Osorio Avatar asked Jul 05 '13 17:07

Alfredo Osorio


People also ask

Can global variables be accessed in functions?

Functions can access global variables and modify them. Modifying global variables in a function is considered poor programming practice. It is better to send a variable in as a parameter (or have it be returned in the 'return' statement).

Is a JavaScript global variable is not accessible from any function?

Global variables can be accessed from anywhere in a JavaScript program.

How do you use a global variable in another function?

If your function has a local variable with same name as global variable and you want to modify the global variable inside function then use 'global' keyword before the variable name at start of function i.e. As you can see modification done to global variable total is now visible outside the function too.

Can global variables be accessed in another file?

Global variables and function names have external linkage. These are accessed from other files by declaring them with the keyword extern.


1 Answers

What's going on here is called "hoisting". Variable declarations that use var and function statements are "hoisted" to the top of their containing scope. (Note that, from ES6 on, let and const have different semantics.) So, to the browser's mind, your code actually looks like this:

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

From MDN:

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

like image 64
lonesomeday Avatar answered Oct 31 '22 10:10

lonesomeday