JavaScript Closures

October 28, 2014 in Web Development Articles

Written by Todd Wright


What I wish I had picked up in Introduction to JavaScript. Pt 2

So, JavaScript is really a simple language. It is a language that is straight forward: what you see is what you get. Here is the problem: Closures are being used all over the place in modern JavaScript, but just because I see them does not mean I get them. This “simple” onClick and mouseOver language has got some sting.

This article is going to introduce a concept which (in my opinion) can be difficult to digest by itself, but is a fundamental (if not THE fundamental) building block to understanding the syntax that is very often used in “modern” JavaScript pages.

The “What” Closure

Obligatory simplified example:

<script language="JavaScript">
var validateForm=function(){
    var checkValue = function(pattern,value){
    }
    //The following calls work. They can "see" the checkValue function
    if (checkValue(//,document.getElementByID(''.) && checkValue(//,form.){
        return true;
    }
    else { return false }
}
// checkValue(//,'abc');  // This fails. – can't "see" the function
</script>

The checkValue variable is available only within the outer validateForm function. The checkValue is a closure. A function defined within another function is a closure. Functions that are defined within another function can “see” the variables within that function – var variables, arguments, and global variables.

Simple. A closure is a function defined within another function. That is pretty simple. The “what” is the easy part. The harder part is the “why” — and, even harder, all the nuances that they enable.

The “Why” Closures

There are many code designs that we can use because of closures. We will start with the building blocks and over the next few articles, show some fantastic applications of this pattern to achieve some mind-blowing code.

First back to var. Free Choice.

Remember the var keyword? The var keyword scopes a variable to the function within which it is defined.

In a prior article, we played with var and saw the dangers of scoping variables in the global namespace. Here it is again: A closure is not automatically in the global namespace. In this example, the checkValue is a variable scoped to the outer validateForm function. In the above example, the only global variable is the validateForm variable.

Chew on this. What would removing the var in front of checkValue mean?

var validateForm=function(){
   # NO var keyword below
   checkValue = function(pattern,value){
   }
   //The following calls work. They can "see" the checkValue function
   if (checkValue(//,document.getElementByID(''.) && checkValue(//,form.){
      return true;
   }
   else { return false }
}

Answer: Removing the var has made that function visible everywhere. We get to choose. We can choose to add a variable to either function scope of global scope. I like choice.

Second: More var. Private variables

<script language="JavaScript">
var createMessage = function(msg){
    var privateMessage = msg
    var show = function(){
        console.log(privateMessage);
    }
    return {'show':show}
}
var happyMessage = createMessage('Hello Friends');
var sadMessage = createMessage('Goodbye Friends');
happyMessage.show();
sadMessage.show();
// This is no good.  This will not work.
//console.log(privateMessage);
</script>

The privateMessage variable is created as a var variable within the createMessage function. It is not accessible outside that function. The closure (show) is making a reference to that variable. We can see variables from the outer function inside a closure. In fact, it gets better. That state – the state of that variable – stays around as long as we hold reference to the show variable. We are passing the show variable back out. That show function is able to be invoked from outside the createMessage function. The specific state of the privateMmessage variable is retained on the “stack” so the show function has access to it.

Did you catch that? We created a private variable that is only accessible from the show function. Do you suppose we can modify that private value? Check it out:

<script language="JavaScript">
var createMessage = function(msg){
    var privatemessage = msg
    var show = function(){
        console.log(privatemessage);
    }
    var setValue = function(msg){
        privatemessage = msg;
    }
    return {'show':show,'setValue':setValue}
}
var happyMessage = createMessage('Hello Friends');
var sadMessage = createMessage('Goodbye Friends');
happyMessage.show();
sadMessage.show();
happyMessage.setValue('Wahoo Glad you are still here!');
happyMessage.show();
sadMessage.show();
</script>

Don’t look now, but I believe this is an implementation of encapsulation; Variable encapsulation in JavaScript using closures.

There are MANY more nuggets that this closure concept enables. Keep an eye out for a few more articles that will dive much deeper into the “Why” and patterns around this.


 

Author: Todd Wright, one of Accelebrate’s instructors

Accelebrate offers private JavaScript training for groups and instructor-led online JavaScript classes for individuals.


Written by Todd Wright

Todd Wright

Todd is a Java developer and trainer specializing in Enterprise Java Technology (J2EE), Perl, and XML related software. Todd is a published author of several software development and design technical training books.


Learn faster

Our live, instructor-led lectures are far more effective than pre-recorded classes

Satisfaction guarantee

If your team is not 100% satisfied with your training, we do what's necessary to make it right

Learn online from anywhere

Whether you are at home or in the office, we make learning interactive and engaging

Multiple Payment Options

We accept check, ACH/EFT, major credit cards, and most purchase orders



Recent Training Locations

Alabama

Birmingham

Huntsville

Montgomery

Alaska

Anchorage

Arizona

Phoenix

Tucson

Arkansas

Fayetteville

Little Rock

California

Los Angeles

Oakland

Orange County

Sacramento

San Diego

San Francisco

San Jose

Colorado

Boulder

Colorado Springs

Denver

Connecticut

Hartford

DC

Washington

Florida

Fort Lauderdale

Jacksonville

Miami

Orlando

Tampa

Georgia

Atlanta

Augusta

Savannah

Hawaii

Honolulu

Idaho

Boise

Illinois

Chicago

Indiana

Indianapolis

Iowa

Cedar Rapids

Des Moines

Kansas

Wichita

Kentucky

Lexington

Louisville

Louisiana

New Orleans

Maine

Portland

Maryland

Annapolis

Baltimore

Frederick

Hagerstown

Massachusetts

Boston

Cambridge

Springfield

Michigan

Ann Arbor

Detroit

Grand Rapids

Minnesota

Minneapolis

Saint Paul

Mississippi

Jackson

Missouri

Kansas City

St. Louis

Nebraska

Lincoln

Omaha

Nevada

Las Vegas

Reno

New Jersey

Princeton

New Mexico

Albuquerque

New York

Albany

Buffalo

New York City

White Plains

North Carolina

Charlotte

Durham

Raleigh

Ohio

Akron

Canton

Cincinnati

Cleveland

Columbus

Dayton

Oklahoma

Oklahoma City

Tulsa

Oregon

Portland

Pennsylvania

Philadelphia

Pittsburgh

Rhode Island

Providence

South Carolina

Charleston

Columbia

Greenville

Tennessee

Knoxville

Memphis

Nashville

Texas

Austin

Dallas

El Paso

Houston

San Antonio

Utah

Salt Lake City

Virginia

Alexandria

Arlington

Norfolk

Richmond

Washington

Seattle

Tacoma

West Virginia

Charleston

Wisconsin

Madison

Milwaukee

Alberta

Calgary

Edmonton

British Columbia

Vancouver

Manitoba

Winnipeg

Nova Scotia

Halifax

Ontario

Ottawa

Toronto

Quebec

Montreal

Puerto Rico

San Juan