Section A. The basics


A. The basics

Let's start with some JavaScript basics. Not only is this a useful exercise for learning JavaScript, it will help you understand how a programming language works.

Case sensitivity

Sacred tradition requires us to say "Hello world" before doing anything serious. Here goes:

   var test = 'Hello world';  alert(Test); 


We immediately encounter our first JavaScript error: Test is not defined.

JavaScript is case sensitive. The variable test is not the same as Test, so JavaScript doesn't recognize it.

Always take care to write names such as getElementById with exactly the right mix of upper- and lowercase characters. If you make even the tiniest mistake (such as getElementByID), JavaScript doesn't understand what you mean.

You'll learn this JavaScript lesson the hard way.

Statements and the ;

Every script consists of a list of statementscommands that tell JavaScript to do something. Take this script:

var test = 'Hello world'; alert(test); 


It contains two statements. The first tells JavaScript to create a variable test and to assign the string 'Hello world' to it. The second tells JavaScript to create an alert box and display the value of test in it.

As you see, I terminate every statement with a semicolon. This tells JavaScript that one statement has ended and that any code that follows is part of a new statement. This is important in cases where there are several statements on one line:

   var test = 'Hello world'; alert(test); 


Without the ; JavaScript would have no way of knowing where the first statement ends and the second begins.

It is customary to put every JavaScript statement on its own line, because that keeps your code readable. In fact, JavaScript was designed with this best practice in mind. Whenever a line of code ends without a semicolon, JavaScript automatically inserts one. The code below works fine:

   var test = 'Hello world'  alert(test) 


Nonetheless, neither of the two previous examples is considered good programming practice. Put every statement on its own line, and terminate the line with a semicolon. CSS wizards have the advantage here, because in CSS every semicolon is required. They can port their semicolon discipline to JavaScript.

When to not use ;

You may not end a line with a semicolon when you use an if, for, or while control structure. This is wrong:

   if (x == 4);  {     x = x * 2;          alert(x);  } 


JavaScript understands this code as:

   if (x == 4)  {          /* nothing */;  } {     x = x * 2;         alert(x); } 


JavaScript is perfectly capable of doing nothing if x is equal to 4, and therefore this if statement generates no error message. Nonetheless, it's probably not what you want.

You'll also learn this nasty little JavaScript feature the hard way. I've wasted plenty of time searching for obscure browser bugs to explain a behavior that was really caused by an incorrect semicolon.

Comments

Some lines contain comments instead of code. Comments are ignored by the script interpreter and are meant for the human beings who are working with your code.

JavaScript has two ways of defining comments:

// This line is a comment /*    This block of lines is a comment */ 


The // characters make the rest of the line they occur on a comment. You may use them after a normal JavaScript statement:

if (node.nodeType == 3) // Safari bug!     node = node.parentNode; 


I often use // to temporarily disable lines of script. For instance, I disabled one line in the addInput() function of Site Survey:

[Site Survey/popup.js, lines 49-56]

function addInput(name,value) {     var mainForm = document.forms[0];    var newInput = document.createElement('input'); // newInput.type = 'hidden';    newInput.name = name;    newInput.value = value;    mainForm.appendChild(newInput); } 


In the real version, the script generated hidden form fields. However, in order to show you how the script works, I disabled this line so that you would see the form fields being generated.

The /* and */ characters define a multi-line comment, just as in CSS. Note that the */ is required: if you open a comment by /* but do not close it, all browsers give error messages.

Code blocks: {}

Curly braces {} define a block of code that counts as a single statement. These blocks usually run only in certain circumstances. For instance, take this function:

function highlight(obj) {     obj.parentNode.className = 'highlight'; } 


The curly braces define the code block that is the function body. The statements in the block are executed only when the function is called. The same happens with the if and for statements:

if (x == 4) {     x = x * 2;     alert(x); } 


The statements enclosed by the curly braces are executed only if x is equal to 4.

Omitting the {}

You may omit the {} when an if, while, or for block contains only a single statement. For instance:

if (x == 4)     x = x * 2; 


If x is equal to 4, x is multiplied by 2. This is valid JavaScript. However, omitting the curly braces may lead to problems. Take this code; it's not wrong, but it might not do what you expect:

if (x == 4)     x = x * 2;     alert(x); 


Again, if x is equal to 4, x is multiplied by 2. Then, whether x is equal to 4 or not, x is alerted. In fact, JavaScript understands the code as:

if (x == 4) {     x = x * 2; } alert(x); 


To prevent this sort of error, it's best to always enclose if and for statements in curly braces.

Note that function bodies must always be enclosed in curly braces, even if they contain only one statement.

Do as I Say

When you go through the example scripts you'll see that I don't always follow this rule. I often omit the {} in an if with only one single statement; and yes, occasionally I encounter a bug because of that.

This is one of the few times I'd like to ask you to do as I say, not as I do.


Operators

Most statements contain at least one operator, a character that tells JavaScript exactly which operation should be performed. Take this code:

   a b; 


Although you may have defined variables a and b, this pseudo-statement doesn't tell JavaScript what to do with them, and produces an error.

Instead, you should give explicit instructions:

var c = a * b; 


This statement contains two operators: the * operator that performs the multiplication of a by b, and the = operator that assigns the result of that multiplication to c.

In general, you don't have to worry about operators. On the whole, you'll use them instinctively and correctly once you know what they mean. The most important exception is the + operator, and we'll discuss its problems in detail in 5B.

Operands

An operator needs operandsvalues on which to perform its operation. If we say a * b, the * operator commands a multiplication to take place. What do we multiply? The values of a and b. The * operator operates on a and b; therefore a and b are the operands of *. Most operators need two operands.

Operator precedence

Take this statement:

var a = x - y * z; 


Which operator goes first: - or *? If you remember your math, you'll know that multiplication comes before subtraction. In technical terms, the multiplication operator has a higher precedence than the subtraction operator.

Therefore, this statement first multiplies y by z, and then subtracts the result from x. The result of this last operation is stored in a. If you want the subtraction to take place first, you use parentheses, just as in normal math:

var a = (x - y) * z; 


This would first subtract y from x, then multiply the result by z, and store the final result in a.

Note that the = operator has a low precedence: it executes only when all other operators have been evaluated. That's why the assignment of the final value of the calculation to a takes place last.

Return Value of =

The = operator's return value is a bit tricky. Take this operation:

var a = 1; 


This in fact does two things:

  1. It assigns the value 1 to the variable a.

  2. Once that's done, it returns this same value 1 to the next operator (if any), just as the * operator in the previous example returned the result of the multiplication to the = operator.

Usually there is no other operator in assignment statements, but occasionally you want to assign the same value to several variables:

var a = b = 1; 


First JavaScript assigns the value 1 to b. Then it takes the return value of the = operator, which is still 1, and assigns it to a. In 5C we'll encounter one situation in which ='s return value is important.


Return value

Every operator returns a value, and it's this value that you want to do something with.

var c = a * b; 


If we multiply a by b, the operation returns the result of this multiplication. The = operator takes this return value and performs its own operation with it: it stores the value in c.

Values

Getting and using values is the whole point of programming. Therefore we'll have to take a closer look at values in general. Take this line:

var a = b * 4; 


4 is a value. b is a variable that contains a value (for instance, 3). If we multiply the value of b by 4 we get another value, 12, which is assigned to variable a. This is a simple example of value manipulation.

Functions as values

Now let's look at a more complicated example:

var test = function () {     alert('Hello world!'); } var otherTest = test; otherTest(); 


In JavaScript, there is no fundamental difference between functions and other values. In this example, the variable test refers to a function. When the value of test is assigned to otherTest, otherTest becomes a function that when executed causes the 'Hello world!" alert to pop up.

Treating functions as values is quite common in event handling. We'll return to this subject in 5I and 7C.

Variables and literals

A value is commonly expressed as a variable or a literal. The difference is simple:

var a = 10; var b = a * 4; 


In this code example, a and b are variables, which means they may contain any value, though right now they contain 10 and 40.

The 10 and 4 are literals: they literally mean 10 and 4, and cannot mean anything else.



ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ISBN: N/A
EAN: N/A
Year: 2005
Pages: 116

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