Section 2.1. Identifying Variables


2.1. Identifying Variables

JavaScript variables have an identifier, scope, and a specific data type. Because the language is loosely typed, the rest, as they say, is subject to change without notice.

Variables in JavaScript are much like those in any other language; they're used to hold values in such a way that the value can be explicitly accessed in different places in the code. Each has an identifier unique to the scope of use (more on this later), consisting of any combination of letters, digits, underscores, and dollar signs. There is no required format for an identifier, other than that it must begin with a character, dollar sign, or underscore:

_variableidentifier variableIdentifier $variable_identifier var-ident

Starting with JavaScript 1.5, you can also use Unicode letters (such as ü) and digits, as well as escape sequences (such as \u0009) in variable identifiers. The following are also valid variable identifiers for JS:

_üvalid T\u0009

JavaScript is case-sensitive, treating upper- and lowercase characters as different characters. The following two variable identifiers are seen as separate variables in JS:

strngVariable strngvariable

In addition, a variable identifier can't be a JavaScript keyword, a list of which is illustrated in Table 2-1. Other keywords will be added over time, as new versions of JavaScript (well, technically ECMAScript) are released.

Table 2-1. JavaScript keywords
break

else

new

var

case

finally

return

void

catch

for

switch

while

continue

function

this

with

default

if

throw

 
delete

in

try

 
do

instanceof

typeof

 


Due to proposed extensions to the ECMA 262 specification, the words in Table 2-2 are also considered reserved.

Table 2-2. ECMA 262 specification reserved words
abstract

enum

int

short

boolean

export

interface

static

byte

extends

long

super

char

final

native

synchronized

class

float

package

throws

const

goto

private

transient

debugger

implements

protected

volatile

double

import

public

public


In addition to the ECMAScript reserved words, there are JavaScript-specific words implemented in most browsers that are considered reserved by implementation. Many are based in the Browser Object Modelobjects such as document and window. Though not a definitive list, Table 2-3 includes the more common words.

Table 2-3. Typical reserved words in browsers
alert

eval

location

open

array

focus

math

outerHeight

blur

function

name

parent

boolean

history

navigator

parseFloat

date

image

number

regExp

document

isNaN

object

status

escape

length

onLoad

string


2.1.1. Naming Guidelines

Any name can be used for variables and functions within code, but there are several naming practicesmany inherited from Java and other programming languages that can make the code easier to follow and maintain.

First, use meaningful words rather than something that's thrown together quickly:

var interestRate = .75;

versus:

var iRt = .75;

You can also provide a data type clue as part of the name, using something such as the following:

var strName = "Shelley";

This type of naming convention is known as the Hungarian notation and is especially popular in Windows development. As such, you'll most likely see it used within the older JScript applications created for Internet Explorer but less often in more modern JS development.

Use a plural for collections of items:

var customerNames = new Array(  );

Typically, objects are capitalized:

var firstName = String("Shelley");

Functions and variables start with lowercase letters:

Function validateName(firstName,lastName) ...

Many times, variables and functions have one or more words concatenated into a unique identifier, following a format popularized in other languages, and frequently referred to as CamelCase:

validateName firstName

This approach makes the variable much more readable, though dashes or underscores between the variable "words" work as well:

validate-name first_name

The newer JavaScript libraries invariably use CamelCase.

The term CamelCase is based on the popularity of mixed upper- and lowercase letters in Perl, and of the camel featured on the cover of the bestselling book, Programming Perl, by Larry Wall et al. (O'Reilly). Wikipedia has a fascinating and dynamic article on this and other naming notations at http://en.wikipedia.org/wiki/CamelCase. Another variation, somewhat tongue-in-cheek and also covered at Wikipedia, is StudlyCaps, at http://en.wikipedia.org/wiki/Studlycaps.


Though you can use the $, number, or underscore to begin a variable, your best bet is to start with a letter. Unnecessary use of unexpected characters in variable names can make the code harder to read and follow, especially for newer JavaScript developers.

However, if you've looked at some of the newer JavaScript libraries and examples, you might notice several new conventions for naming variables. The Prototype JavaScript library is a strong influence in this regardso much so that I think of the rise of new naming conventions as the "Prototype effect."

2.1.2. The Prototype Effect and the Newer Naming Conventions

Many new or relatively newer naming conventions introduced into JavaScript are based less on making the language more readable and more on making JavaScript look and act like other programming languages, such as Java, Python, or Ruby.

As an example, JavaScript has several object-oriented-like capabilities, including the ability to create private members for an object. These are properties/methods that are accessible only within another function of the object, not directly by applications using the objects.

There is nothing inherent in JavaScript that marks an object as being private, as opposed to public. However, an increasing number of JavaScript developers are following both Java and Python naming conventions and are using the underscore (_) to mark a variable as private:

var _break    = new Object(  ); var _continue = new Object(  );

The Prototype library also introduced the use of the $ to designate shortcut methodsways to access references to objects without having to write out the specifics:

$(  ); $A(  );

Class objects start with an uppercase character, functions and variables start with lowercase, and all use CamelCase, discussed earlier. Abbreviations are reformatted into this notation (i.e., XmlName, as compared to XMLName), and the only exceptions are constants (variables treated as unchanging static values), which are typically written out all uppercase: MONTH as compared to month or Month.

In names for functions, a verb should be used; nouns are used for variables:

var currentMonth; function returnCurrentMonth...

If included in an isolated block of JavaScript meant for distribution (typically referred to as a JavaScript library or package), identifiers for functions and global variables should have a package reference to prevent name collision (conflict between names):

dojo_someValue; otherlibrary_someValue;

Iterator variables (used in for loops and other looping mechanisms) should be simple, and consist of i, j, k, and so on, down the alphabet (a holdover from long, long ago when programming languages such as FORTRAN required that all integers begin with the letters i, j, etc.).

There are other conventions established with the newer JavaScript development, most of which are detailed quite nicely in a document put out by the Dojo organization, JavaScript Programming Conventions (available at http://dojotoolkit.org/js_style_guide.html at the time of this writing).

I agree with, and adhere to, many of the conventions covered in this section and the last. The one convention I do take exception to is the use of the dollar sign in the Prototype library. It adds an unnecessary element of obfuscation to the language that makes it difficult for newer developers to understand what's going on.

Regardless of personal preferences, there is nothing mandatory or magical about the naming conventions I've outlined, other than the few requirements enforced by the JavaScript engine. They are a convenience.

We'll cover the Prototype library in detail in Chapter 14, but for now, when you see these naming conventions used in sample code at sites as you start to explore, you'll know that I haven't left great chunks of JavaScript functionality out of the book.





Learning JavaScript
Learning JavaScript, 2nd Edition
ISBN: 0596521871
EAN: 2147483647
Year: 2006
Pages: 151

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net