AJAX - The Complete Reference

(avery) #1

568 Part IV: Appendixes


function myFunc()
{
var local1 = "Locals only";
global3 = true;
}

Commonly, JavaScript developers make assumptions about scoping rules with var that
aren’t quite true. For example, a var statement found within a for loop does not scope that
value to the loop. In this case, j is scoped to either the function it is within or the global
space if it is outside a function or object.

for (var j = 0; j < 10 ; j++)
{ /* loop body */ }

Further, within a block, a var statement does nothing different than it would otherwise:

if (true)
{
var x = "Not block local!";
}

Under JavaScript 1.7 as supported in Firefox 2+, we see the introduction of the let
statement, which makes things a bit more complicated. You can locally bind values to the
scope of a let statement and accomplish exactly the two aforementioned ideas:

for (let j = 0; j < 10 ; j++)
{ /* loop body with j being loop local */

if (true)
{
let x = "I am block local!";
}

Constants
There are no user-defined constants in JavaScript 1.X implementations. For style concerns, if
you treat a variable as a constant you should consider casing it in all capitals:

LUCKYNUMBER = 3; // fake constant

NNOT EOTE We didn’t use the var here, though it is global, because that keyword actually hurts
readability.

Operators


JavaScript has a wealth of operators that are similar to other C-like languages, but with
some additions to deal with weak typing and some omissions due to the fact the language
generally does not require the programmer to perform memory management.
Free download pdf