July 2007 Technical Tip A warning against omitting VAR from JavaScript variables

One of our instructors recently told me that he had encountered a new problem with JavaScript. He said that if the first occurrence of a variable is in a function, and if that variable is not declared with VAR, then that variable will be treated as if it was declared globally. I thought his discovery was significant and I set out to write a simple program to document this "feature" of JavaScript. My friend was right! The sample program follows:


<html>
<script language="JavaScript">

function f1()
{
  var a = 2;
  alert("The value of a is " + a);
}

function f2()
{
  alert("The value of a is " + a);
}

</script>

<form action="#">
<input value="Do function f1" type="button" onclick="f1()">
  
<input value="Do function f2" type="button" onclick="f2()">
</form>

</html>

If you run this program and click on the "Do function f1" button, you'll see "The value of a is 2", and if you click on the "Do function f2" button, you'll see an error dialog indicated that variable a is undefined. This is as you would expect, because variable a was declared within function f1 and is therefore local to f1 only. Variable a was never declared within function f2.

But if the first statement in function f1 is changed from "var a = 2" to simply "a = 2" then variable a will, in fact, be treated as if it was declared globally, and if you click on the "Do function f2" button, you'll see "The value of a is 2".

I should mention that this was tested with Internet Explorer only. I do not know how other browsers would behave.

JavaScript is a less-than-perfect language. But it has its place. Use it as intended and it will serve you well. If you need training on HTML, JavaScript, XML, J2SE, servlets, JSPs, or web services, we hope you will consider Caliber Data Training when deciding upon a training provider.


Go to the articles index. Written by Bill Qualls. Copyright © 2007 by Caliber Data Training 800.938.1222