w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Why my global variable is not accessible within a function?

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

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

Javascript only has function scope, and all variables declared within a function are hoisted to the top so they are available throughout the function. The first alert in the OP's original version was using the uninitialized, hoisted, local variable, which is why it printed undefined.

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.