View Single Post
Old 01-29-2013, 06:34 PM   PM User | #3
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,455
Thanks: 0
Thanked 498 Times in 490 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
All the local variables referenced within a function are declared as local variables before any of the code in the function runs. Effectively it is as if you had one var at the top of the function with all of the variables declared using var within the function as a comma separated list after it - as that is where all the declarations run it makes your code easier to read if you actually put the declarations there.

With modern strict JavaScript all variables need to be declared and your script will fail to run if you try to use one that isn't declared. Also by wrapping ALL of your code in anonymous functions you can avoid using global variables almost completely - with only one or two being needed to provide access to shared libraries.

A strict and unobtrusive version of that code would look like this:

Code:
(function() {"use strict";
var a = 123;

function f() {
var a; // declaration moved to where it is actually run
alert(a); // used just to demonstrate that at this point the local variable is declared but undefined
a = 1;
alert(a);
}

f();
})();
With that code the first variable set to 123 is local to the outer function and so will not clash with any similarly named variable in any other script you add to the same web page.
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/
felgall is offline   Reply With Quote
Users who have thanked felgall for this post:
chickentulip (01-30-2013)