Search code examples
javascriptfunctionvariablesscopeundeclared-identifier

Undeclared JavaScript variable in functions overriding over uses


I have two function examples as follows

function call1() {
    variable = "test string";
}

function call2() {
    variable = responseFromAJAX();

    document.title = variable;

    setTimeout(function() { call2(o); }, 1000 );
}

If there anyway that the undeclared variable "variable" can be overridden by either function? even when "variable" is not declared out the scope of the functions?

Many thanks


Solution

  • If there anyway that the undeclared variable "variable" can be overridden by either function?

    Yes. Unless you're in strict mode, assigning to an undeclared variable creates a global variable implicitly (I call it The Horror of Implicit Globals). So either function can write to it. Fortunately, strict mode put a stop to implicit globals.