Closures in JavaScript

October 28, 2014 in JavaScript 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.



Contact Us:

Accelebrate’s training classes are available for private groups of 3 or more people at your site or online anywhere worldwide.

Don't settle for a "one size fits all" public class! Have Accelebrate deliver exactly the training you want, privately at your site or online, for less than the cost of a public class.

For pricing and to learn more, please contact us.

Contact Us Train For Us

Toll-free in US/Canada:
877 849 1850
International:
+1 678 648 3113

Toll-free in US/Canada:
866 566 1228
International:
+1 404 420 2491

925B Peachtree Street, NE
PMB 378
Atlanta, GA 30309-3918
USA

Subscribe to our Newsletter:

Never miss the latest news and information from Accelebrate:

Microsoft Gold Partner

Please see our complete list of
Microsoft Official Courses

Recent Training Locations

Alabama

Huntsville

Montgomery

Birmingham

Alaska

Anchorage

Arizona

Phoenix

Tucson

Arkansas

Fayetteville

Little Rock

California

San Francisco

Oakland

San Jose

Orange County

Los Angeles

Sacramento

San Diego

Colorado

Denver

Boulder

Colorado Springs

Connecticut

Hartford

DC

Washington

Florida

Fort Lauderdale

Miami

Jacksonville

Orlando

Saint Petersburg

Tampa

Georgia

Atlanta

Augusta

Savannah

Idaho

Boise

Illinois

Chicago

Indiana

Indianapolis

Iowa

Ceder Rapids

Des Moines

Kansas

Wichita

Kentucky

Lexington

Louisville

Louisiana

Baton Rouge

New Orleans

Maine

Portland

Maryland

Annapolis

Baltimore

Hagerstown

Frederick

Massachusetts

Springfield

Boston

Cambridge

Michigan

Ann Arbor

Detroit

Grand Rapids

Minnesota

Saint Paul

Minneapolis

Mississippi

Jackson

Missouri

Kansas City

St. Louis

Nebraska

Lincoln

Omaha

Nevada

Reno

Las Vegas

New Jersey

Princeton

New Mexico

Albuquerque

New York

Buffalo

Albany

White Plains

New York City

North Carolina

Charlotte

Durham

Raleigh

Ohio

Canton

Akron

Cincinnati

Cleveland

Columbus

Dayton

Oklahoma

Tulsa

Oklahoma City

Oregon

Portland

Pennsylvania

Pittsburgh

Philadelphia

Rhode Island

Providence

South Carolina

Columbia

Charleston

Spartanburg

Greenville

Tennessee

Memphis

Nashville

Knoxville

Texas

Dallas

El Paso

Houston

San Antonio

Austin

Utah

Salt Lake City

Virginia

Richmond

Alexandria

Arlington

Washington

Tacoma

Seattle

West Virginia

Charleston

Wisconsin

Madison

Milwaukee

Alberta

Edmonton

Calgary

British Columbia

Vancouver

Nova Scotia

Halifax

Ontario

Ottawa

Toronto

Quebec

Montreal

Puerto Rico

San Juan

© 2013-2019 Accelebrate, Inc. All Rights Reserved. All trademarks are owned by their respective owners.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.