Your privacy matters: This site uses cookies to analyze site usage and provide social media features. Learn More.

JavaScript Variable Scope Tutorial

September 04, 2014 in JavaScript Articles

Written by Todd Wright


What I Wish I had Picked up in Introduction to JavaScript

I’ve been doing JavaScript for a few years, quite a few actually. I learned JavaScript back in the 1990s from the masters who were concerned with rocking the image swaps, scrolling banners, and onSubmit event handlers. This was a great time when the bulk of JavaScript for a page fit on a single editor page and browser inconsistencies were primarily handled by not using a particular feature.

The world changed. JavaScript is extremely popular (and powerful!). This language enables all kinds of coolness that abounds on the dynamic web today. A scan of the most popular sites will see a vast array of tricks that to the developer’s eye will stand out as a fantastic bit of code. The modern web app is usually an aggregation of 3 distinct languages (yes, you need them all): HTML, JavaScript, and CSS. Of the three, JavaScript can often be the trickiest.

Var Keyword

The var keyword in JavaScript was often taught as syntactical sugar, optional. It is not. As your code base of JavaScript explodes, the nuances of the var keyword become quite important! I am still amazed how often a JavaScript developer misunderstands the importance of good style and good habits when it comes to var. The var keyword scopes a variable. Two scopes are commonly defined, global and local.

Global scope are all those variables that are defined at the top level of your code.

<script language="javascript">
var msg="Global scoped variable";
</script>

The msg variable above is available everywhere in the page. The global scope is incredibly powerful for sharing variables around (remember, variables point to things: values, functions, and objects objects). The danger that everyone speaks about is the pollution of that namespace. There is only one global scope, and once you add a variable to that scope, another definition of that variable in the global scope is a collision.

Local scope is a set of variables that are available within a smaller set of code lines – generally a top-level function. Variables defined within a local scope are available to that narrower scope, but not the outer scopes.

<script language="javascript">
var msg="Global scoped variable";
var sayMessage = function(){
   var innermsg = "Inner-scoped variable";
   console.log(innermsg);
}
sayMessage();
console.log(innermsg); //The variable is not visible here.
</script>

Variables are defined with the var keyword, which places them in a scope. Assigning a value to a variable without the var keyword implicitly creates the variable in the global scope. Did you catch that? That is a really important concept! JavaScript will implicitly add your new variable to the global scope if you forget the var keyword.

<script language="JavaScript">
var msg="Global scoped variable";
var sayMessage = function(){
   innermsg = "Inner-scoped variable"; //Oops! Missed the var keyword!
   console.log(innermsg);
}
sayMessage();
console.log(innermsg); //The variable is now visible!
</script>

JavaScript is exploding on our pages. It is not unheard of to have hundreds (or thousands) of lines of JavaScript on a page. A very simple practice of using var to declare your variables will save you hours of painful JavaScript debugging!!

Keep an eye out for a few more articles that will dive much deeper into the “Why” and patterns around this scoping topic.

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

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

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