JavaScript Variable Scope

In this tutorial I will demonstrate some of the fundamental rules of variable and object scope in JavaScript. We all know how important it is to understand how scope works in each programming language, and not every language applies the same rules. With a clear understanding of how this works in JavaScript, you will be well equipped to write code that is easier to read and will avoid stepping on others’ (and your own) toes. If you want to skip the reading you can go right to a complete working example.

As a side note, one of my favorite things about JavaScript is “closures”. We won’t go over closures in this tutorial, but I will probably write another tutorial about them in the future. Some discussion about JSON will probably be appropriate for that tutorial as well.

JavaScript Global Variables

In JavaScript global variables and objects are accessible by all code under the “window” object, at all levels. Global variables can be created a few ways.

// omitting "var" from the definition will create the variable under the "window" object, wherever the variable is defined.
a ="I am a string.";// using var will create the variable under the window object only if the code is executed at the document level.var b =101;// the following explicitly defines the variable as a property of the window object.
window.c=22.5;

Use Globals Responsibly

While variables with global scope have their purpose, you will probably not want to define everything at the window object level. The reason is that you, or someone else, may inadvertently read or alter a value that shouldn’t be. As an example let’s suppose you are writing some JavaScript on a page where another JavaScript author’s code has been included somewhere in the document. Their code has something to do with fruit, and so does yours.

// a different author's code
fruit ="apple";

Later in the document you have your own code.

// your code.
fruit ="pineapple";

Oops! You’ve changed the value of their variable.

Take Advantage Of Local Scope

You’ll need to be careful defining variables without “var”. To be safe I like to use “var” or the parent object’s name when defining variables. Let’s look at another example.

// a globally defined variablevar name ="John";function HerName(){// this is supposed to be a local variable, but we forgot to use "var"
name ="Sarah";return name;}
alert('His name is '+ name);// alerts 'John'
alert('Her name is '+ HerName());// alerts 'Sarah'
alert('His name is '+ name);// alerts 'Sarah'

It’s easy to forget that if a variable is defined in a function, omitting var or the parent object name will define a global variable, or access one that already exists.

A Complete Variable Scope Test

If you would like to see some of the items discussed feel free to copy this example segment and try it out yourself.