Resolving Reference Errors and Variable Scope

Problem
You want to know how to troubleshoot the following scope-related errors that may occur at runtime.

ReferenceError: variableName is not defined
ReferenceError: assignment to undeclared variable
ReferenceError: Can't find variable: variableName

Solution
JavaScript uses variable scoping. That is, when a variable is declared, it is given scope. Variables can only be used in the functions they’re declared in. As a result, variables with global scope aren’t contained in any function. To address these potential errors, be sure not to access variables outside their scope. If you need access to a variable outside its enclosing function, the solution is to move it out of the function to a higher scope.

Examples

// Strict mode enabled.
"use strict";

// A function defined with a variable wrapped in it.
function doSomething() {
    var aVariable = 5;
}
// This causes a ReferenceError because the variable is only within the function's scope.
console.log(aVariable);

// Calling the function and then trying to access the variable fails for the same reason.
doSomething();
console.log(aVariable);

// This works since anotherVariable is global in scope and not restricted to the body of the function.
var anotherVariable = "MTV Generation";
function doSomethingElse() {
    anotherVariable = "Millennials";
}
console.log(anotherVariable);

// Prints Millennials because the function that modifies the variable was called first.
doSomethingElse();
console.log(anotherVariable);

// Prints false because yetAnotherVariable is defined globally, outside the function's scope.
var yetAnotherVariable = false;
function turnTruthy() {
    var yetAnotherVariable = true;
    return(yetAnotherVariable);
}
console.log(yetAnotherVariable);

// This still prints false, because the function contains its own variable with the same name. It doesn't modify the global one.
turnTruthy();
console.log(yetAnotherVariable);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s