JavaScript Editor Free JavaScript Editor     JavaScript Debugger 




Main Page

Previous Page
Next Page

4.2. Variables

Unlike many other programming languages, in JavaScript, variables are not strongly typed, which means that what once contained a number could now be a string. This can sometimes cause some issues when developing on the client side; think about the idea of running across a string when a number is expected. A situation like that could prove somewhat embarrassing, especially because applications are like dogs; they can smell fear. This explains why applications always fail during a demo to upper management.

The names of variables in JavaScript consist of alpha characters followed by a number. The underscore character is also permitted; I usually use it to remind myself that a particular variable is not to be touched. Along the line of the wires that hold up Buck Rogers' spaceship, if you mess with it, bad things could happen.

As with many programming languages, variables in JavaScript have a scope. Before you have an attack of paranoia ("They're watching me!"), please allow me to explain what scope is in reference to variables. Variable scope refers to where the variable is defined. In JavaScript, variables can have either local scope or global scope.

In local scope, the variable is defined within a particular function. The simplest way to explain it is by examining the two functions in Listing 4-2. The first function, Jeckle, defines a variable named monster. The second function, Frankenstein, also defines a variable named monster. Because both variables are local, Jeckle's monster is a different monster than Frankenstein's.

Listing 4-2. Two Local Variables

function Jeckle() {
  var monster = 'Mister Hyde';
}

function Frankenstein() {
  var monster = 'Bob';
}

Global scope refers to variables that are defined throughout the entire page. They are defined in one of two ways, either using a var and declaring the variable outside a function, or omitting the var and declaring it within a function. I don't have a problem with the first method of declaring a global variable, but I have some definite issues with the second. All that it takes is one case of "sausage fingers"; a mistyped variable name, and I'm debugging for hours.


Previous Page
Next Page

Bitcoin Gambling - The Original Crypto Dice Game


JavaScript Editor Free JavaScript Editor     JavaScript Debugger


©