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();
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).
Global variables can be accessed from anywhere in a JavaScript program.
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.
Global variables and function names have external linkage. These are accessed from other files by declaring them with the keyword extern.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With