Resolving Reference Errors and Variable Scope

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

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.


// 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.

// Calling the function and then trying to access the variable fails for the same reason.

// 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";

// Prints Millennials because the function that modifies the variable was called first.

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

// This still prints false, because the function contains its own variable with the same name. It doesn't modify the global one.

Leave a Reply

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

You are commenting using your 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 )


Connecting to %s