Chapter 2. Variables and JavaScript Syntax

In the midst of teaching you how and where you add script to your pages, the previous lesson introduced the following simple script:

function inlineScript() {
    var message = "Hello, World!";
    alert(message);
}

inlineScript();

To fully understand what this code does, it's important to know the basics of the JavaScript language. The core of any language is its syntax — a set of rules that dictate how certain pieces of the language fit together. Think of a spoken language and how difficult it would be to communicate with others if that language did not have a set of rules that defined how words are arranged into complete and understandable sentences. The same is applicable to programming languages. In the case of JavaScript, the browser wouldn't know what to do with your code if it weren't for the rules set forth by the language specifications. Syntax defines how very small pieces of code fit together in order to perform some kind of work.

This lesson focuses on the syntax of one line of code in the listing at the top of the page — the variable declaration:

var message = "Hello, World!";

In this lesson, you learn about variables and the syntax required to make them.

VARIABLES

Developers write programs to make working with data easier. Large amounts of data are typically stored outside the program, via the file system or a database, but many times that data is brought into the application and stored in the computer's memory. Because of this, all programming languages need some way to access the data stored in memory in order to perform work on it.

Variables are parts of a programming language that grant programmers the ability to store and retrieve data stored in memory. You can think of a variable as a box — the box is empty when you create the variable, and the box is full when you assign that variable to hold data.

Some languages are very strict as to what type of data you can put in a particular box. These types of languages are called strongly-typed languages. For example, some languages have boxes for numbers and numbers only — trying to put pieces of text in a box for numbers results in an error.

JavaScript is not one of these strongly-typed languages. Instead, it is a loosely-typed language — it sees a variable as a box that can hold any type of data at any given time. That box may grow or shrink to accommodate the data you put into it, but it does not discriminate between what types of data can fit in the box. This means that a variable can contain a text value at one time, and a number value at another.

Defining a variable in JavaScript requires the use of a variable declaration statement. A statement is a small piece of code that performs some kind of action. Any given program is made up of one or more statements in a specific sequence. The following code shows a variable declaration statement:

var myVariable;

Most JavaScript statements end with a semicolon, as shown in this code. But it is also valid to omit them, as shown in the following code:

var myVariable

However, omitting the semicolon is considered a bad programming practice and is strongly discouraged. This code is considered bad code.

Variable declarations begin with the var keyword, a word reserved by the language for a specific use. The var keyword is used specifically for declaring variables. Following the var keyword is the variable's identifier, or name. Identifiers are made up of one or more characters, and they must follow these rules:

  • An identifier's first character must be a letter, an underscore, or a dollar sign. Many JavaScript libraries make extensive use of the dollar sign. So, it is suggested that you avoid using it.

  • All other characters can be letters, whole decimal numbers (0–9), underscores, or dollar signs.

  • An identifier cannot be the same as a keyword or reserved word (more on these later).

Note

An identifier should briefly describe what the variable contains.

It is important to note the casing of each letter in the variable's identifier. JavaScript is a case-sensitive language: It distinguishes between uppercase and lowercase letters. The previous identifier, myVariable, is not the same as myvariable, Myvariable, mYVariable, or any such variation. It's important to always be aware of an identifier's case, as failing to do so is a very common cause of errors.

The myVariable identifier uses what's called camel-case. This means that the first letter of the identifier is lowercase, and each word in the identifier starts with an uppercase letter. Camel-casing isn't a requirement of JavaScript, but most of JavaScript's built-in identifiers use camel-case. As a programmer, it's a good idea to follow the conventions of the language you're using. In the case of JavaScript, that means following the camel-casing guidelines when naming your own identifiers.

The variable declaration statement in the previous code doesn't contain any data. It has been declared, but it has not been initialized, or assigned a value. To assign data to a variable, use the equals sign (=), also known as the assignment operator, to assign a value to the variable. An operator is a symbol or keyword that takes one or more operands as input and performs an action on those operands.

var myVariable;
myVariable = "some text";

This code declares and initializes myVariable in two separate statements. The first statement is a declaration statement (declaring the variable with the var keyword), and the second statement is an initialization statement (giving the variable an initial value). Notice there is no var keyword used in the initialization line. The var keyword is used only for declaring variables. Once a variable is declared, it is no longer necessary to use var for that variable.

The operands in an assignment operation, as shown in the initialization statement in the previous example, are on both sides of the assignment operator (the equals sign). The operand on the right is an expression or value that is assigned to the operand on the left (the variable).

Using two statements, as in the previous example, is sometimes necessary, as the data for a variable may not exist at the time the variable is declared. However, a variable can be declared and initialized in one statement. The following code shows this:

var myVariable = "some text";

Using one statement is preferred, as it is easier to read and results in a smaller file size.

A variable's value can be overwritten with another value at any time. Using the myVariable from the previous example, the following code overwrites the "some text" value with that of a number:

myVariable = 100;

The variable now contains the number 100. There is no limit to the number of times a variable can be overwritten.

A variable can also be assigned the value contained in another variable. The following line creates a new variable called myVariable2, and it is initialized with the value contained within myVariable:

var myVariable2 = myVariable;

So now the myVariable2 variable contains a value of 100. Even though these two variables contain the same value, and it may look as if they are linked, they are, in fact, independent from one another. In other words, modifying the value contained in myVariable has no effect on the data in myVariable2. This variable independence comes from the fact that numbers are a primitive data type in JavaScript.

Primitive Data Types in JavaScript

A data type is a type of value represented in a programming language, such as numbers, text, and true/false values (among other things). Primitive data types are the basic types of data provided by a programming language. They are the building blocks for more complex data types.

JavaScript has five primitive data types. They are:

  • Number

  • String (text)

  • Boolean

  • Undefined

  • Null

JavaScript's primitive data types hold only one value at a time and are immutable. This means that once a primitive value is created, it cannot be changed. Instead, the variable's original value must be destroyed and replaced with a new value. A primitive variable directly contains the value it is assigned. Assigning a variable the value of a primitive data type copies the value of the second variable, and that copy is assigned to the first variable.

Consider the following code, which recreates the myVariable and myVariable2 variables:

var myVariable = 5,
    myVariable2 = myVariable; // copies the number and assigns copy

myVariable = 6;               // destroys old number value and assigns new
                              // number value in 2nd variable still intact

Before I discuss this code, you undoubtedly noticed some new syntax at the end of lines two, three, and four. These are comments. Comments are human-readable annotations in code. They are ignored by JavaScript and are meant to provide information to anyone reading the code. The types of comments presented in the previous code are single-line comments. They begin with two forward slashes (//), and anything after the slashes is considered a comment. Again, comments are completely ignored by JavaScript, but they give the reader insight about particular lines of code.

Something else you might have noticed is a comma separating the initialization of the myVariable and myVariable2 variables, along with the omission of the var keyword in the second line. The first two lines of this code initialize two variables in a single statement. These multiple variable initialization statements begin with the var keyword, and each subsequent variable initialization is separated with a comma. You can initialize as many variables as you want within a single statement. Just start the statement with var, separate each initialization with a comma, and end the statement with a semicolon.

Note

It does not matter if you initialize variables in one or multiple statements. It's a personal preference. For the sake of clarity, this book opts to use multiple statements to initialize variables.

The first line of code initializes the myVariable variable as containing a value of 5. This value is of the Number data type. The second line of code initializes the myVariable2 variable by copying the value contained within myVariable and assigning that copy to myVariable2. The third line of code reassigns a new value of 6 to myVariable — destroying its original value of 5. But myVariable2 still contains a value of 5, since it was assigned a copy of myVariable's original value. Thus, both variables are separate and independent of each other.

Every time a variable containing a value of a primitive data type is used in code, a copy of that value is made and used in its place. The only way to modify a variable's value is to assign the variable a new value.

Numbers

JavaScript is different from most other languages in that it does not distinguish between different types of numbers, such as integer and decimal numbers. Instead, all numbers are represented by the Number type, which consists solely of floating-point numbers, rational numbers with a very large value range.

In most JavaScript applications, numbers are used as numeric literals. This means that numbers appear directly in the code. The examples up to this point have used whole number, or integer, literals, like the following code:

var myNumber = 5;

But you can also use a numeric literal to assign a number with decimals, like this:

myNumber = 3.14;

Numbers are primarily used to perform mathematical calculations with arithmetic operators.

Using Arithmetic Operators

JavaScript has several operators to perform arithmetic calculations. The following table lists them:

Arithmetic Operators

OPERATOR

NAME

DESCRIPTION

+

Addition

Adds the operands together

-

Subtraction

Subtracts the right operand from the left operand

*

Multiplication

Multiplies the operands together

/

Division

Divides the left operand by the right operand

%

Modulus

Divides the left operand by the right operand and returns the remainder of the operation

Consider the following line of code:

var myNumber = 2 + 2;

This code creates a variable called myNumber. Its value is the result of a mathematic operation adding 2 and 2 together; thus, the value assigned to the myNumber variable is 4.

Mathematical operations are not limited to using numeric literals; variables containing a numeric value can be used in any mathematical expression. The following code uses the myNumber variable created earlier in another mathematical calculation:

myNumber = myNumber - 4;

Remember that assignment operations always go from right to left. So the expression on the right side of the equals sign (myNumber - 4) is evaluated, and the resulting value is assigned to the variable on the left side of the equals sign. Since myNumber's value is 4, this code is essentially the same as the following:

myNumber = 4 - 4;

Arithmetic operations are not limited to one operation per statement; a statement can contain multiple operations, like the following code:

myNumber = 1 + 2 * 3 – 4 / 2;

Executing this statement results in the myNumber variable's containing a value of 5. JavaScript's arithmetic operators have a precedence order similar to the "My Dear Aunt Sally" order in mathematics. Multiplication and division operations have a higher precedence than addition and subtraction, so they execute first. The previous code could be rewritten to the following code after the multiplication and division operations have been performed:

myNumber = 1 + 6 - 2;

Also as in mathematics, you can use parentheses to give a higher precedence to certain operations. The following code adds some parentheses to the previous code sample:

myNumber = (1 + 2) * 3 - 4 / 2;

By placing parentheses around the 1 + 2 operation, you give it a higher precedence than multiplication or division, so it is executed first, followed by the multiplication and division operations, and finally by the subtraction operation. Because the 1 + 2 operation is executed first, the result value has changed from 5 to 7.

Operator precedence determines the outcome of mathematical operations. So it's important to keep operator precedence in mind when performing them.

The final operator, the modulus (or remainder) operator, is represented by a percent sign (%). It performs a division operation on the two operands and returns the remainder of the quotient. The following code demonstrates this:

var remainder = 3 % 2; // returns 1
var remainder2 = 2 % 2; // returns 0

The modulus operator is very handy when you're testing whether a numeric value is even or odd. If the result of a modulus operation by 2 is 0, the number is even. If it is any other number, the number it's odd. Look at the following code:

var isEven = 4 % 2; // 0 - so even
var isOdd = 1 % 2; // 1 - so odd

When a Number Is Not a Number

There are times when a numeric operation fails, such as one that divides by zero or breaks some other mathematical rule. Instead of registering an error and halting code execution (as many other languages do), JavaScript uses a special numeric value called NaN, meaning Not a Number, to indicate that a mathematical operation failed. The following code results in a value of NaN, since it is illegal to divide by zero:

var nan = 1 / 0;

Any operation involving a NaN value always results in NaN. This has the side effect of possibly ruining mathematical operations that contain multiple steps.

Strings

Strings are text values — sequences of zero or more characters. Strings are delimited by double-quote (") or single-quote characters ('). The following code shows two valid strings:

var str1 = "Hello, World";
var str2 = 'Hello, World (again)';

A string beginning with a double quote must end with a double quote; likewise, a string beginning with a single quote must end with a single quote. For example, the following code is not correct and results in an error because the beginning and ending quotes don't match:

var str3 = 'Hello, World (yes again!)"; // invalid string literal

It is, however, perfectly fine for a string delimited with double quotes to contain single quotes, like this:

var str4 = "Hello, Jeremy's World";

Similarly, strings delimited with single quotes can contain double quotes:

var str5 = 'Jeremy said, "Hello, World!"';

Unlike other languages, JavaScript does not discriminate between the type of quotes used to delimit strings. Using single quotes does not change how JavaScript treats the string compared to using double quotes. They're all the same, so which type of quote you use to delimit strings is completely up to you. The examples in this book primarily use double quotes.

A string delimited with single quotes cannot use a single quote inside the string. The following code is incorrect and will generate an error:

var str6 = 'Hello, Jeremy's World'; // error

This is incorrect because JavaScript thinks that the string ends after the y in 'Hello, Jeremy'. It treats the second single quote as the end of the string and doesn't know what to do with the text s World';. The same is true for double-quote characters in a string delimited with double quotes, like this:

var str7 = "Jeremy said, "Hello, World!""; // error

JavaScript thinks the string in this statement is "Jeremy said, ", and it again doesn't know what to do with the remainder of the statement: Hello, World!"";.

In addition to quotation marks, JavaScript has many other special characters that cannot be typed within a string. They can, however, be represented with escape sequences. Think of an escape sequence as an HTML entity: It is a set of characters that represents a particular keystroke when rendered.

For example, HTML entities start with an ampersand (&) and end with a semicolon. The " HTML entity looks funky in the HTML markup, but it renders as a double quotation mark in the browser. Similarly, the " escape sequence in JavaScript looks funky in the code, but it is interpreted as a double quotation mark when it occurs in a JavaScript string.

As an example, the following code revisits the str7 variable declaration and assigns it a string value containing escape sequences:

var str7 = "Jeremy said, "Hello, World!""; // valid string

Escape sequences in JavaScript begin with a backslash, and are followed by one or more characters to denote the special character the escape sequence represents. The following table lists the more commonly used escape sequences:

Escape Sequences

ESCAPE SEQUENCE

DESCRIPTION

New line

Tab

'

Single quote (used when the string is delimited with single quotes)

"

Double quote (used when the string is delimited with double quotes)

\

Backslash

Escape sequences are used when you want to store such a character in a literal string.

Modifying Strings

Like the Number data type, strings are immutable. A string value cannot change once it has been created. Modifying a string value involves destroying the original string value and replacing it with a different value.

Say a variable called str1 contains a string value of "This is a string.". The following code demonstrates this:

var str1 = "This is a string.";

The string value assigned to str1 cannot technically be altered; however, a concatenation, or joining, operation can use the original value contained within str1 and join it with another string value to create a new string value.

Concatenating two or more strings requires the use of the concatenation operator: the plus sign (+). The following code concatenates the original string value in str1 with another string value to modify the data contained within str1:

str1 = str1 + " Hello, World!";

The value now contained within str1 is "This is a string. Hello, World!".

Focus on the code that appears to the right of the assignment operator (the equals sign). This expression is a concatenation operation. The first operand retrieves a copy of str1's value (remember that values are not used directly; they are copied). The second operand is a string literal, and the concatenation operation joins the two values into one value — a value that is then assigned to the str1 variable.

Note the space before Hello in the string literal. If the space had been left out, the concatenated string would be "This is a string.Hello World!". JavaScript will not format strings automatically for you; you must do that yourself.

The same principle can be applied to multiple variables. Look at this code:

var firstString = "This is a string.";
var greetingString = "Hello,";
var name = "Jeremy";
var finalString = firstString + " " + greetingString + " " + name + "!";

This code initializes four strings. The first three are simple strings, and the fourth concatenates the first three into a greeting. Notice that this time, the first three string values do not contain spaces to help with formatting. Instead, the concatenation operation in the fourth line of code inserts spaces as needed. So the value assigned to finalString is this: "This is a string. Hello, Jeremy!".

Converting Numbers to Strings

String concatenation may be confusing at first, especially since the + operator sign is typically used for mathematical operations. This operator pulls double duty as an addition operator and a string concatenation operator in many languages. In JavaScript, the confusion comes from the use of the + operator with values of differing types. Look at the following code as an example:

var possiblyConfusing = "This is the number " + 1;

This code declares and initializes a variable called possiblyConfusing. The expression on the right side of the equals sign consists of a string value, a + operator, and a number. JavaScript is smart enough to know that the string "This is the number " cannot be used in a mathematical operation. Therefore, JavaScript converts the number 1 to a string and concatenates the two operands together. The value contained within the variable is "This is the number 1".

When a string is involved in an operation consisting of the + sign, as in the previous line of code, all non-string values to the right of the string are converted to string values. The operand to the left of the operator maintains its original value, but the end result is a string value

Keep that in mind as you look at the following code and determine the result of the operation:

var probablyConfusing = 1 + 2 + "45";

In this code, the expression to the right of the = operator consists of three operands. The first two are number values, and the third is a string. Since the two numbers are to the left of the string, they are treated as numbers, and the + operator performs an addition operation. So this code can be simplified to this:

var probablyConfusing = 3 + "45";

Now JavaScript sees a number value and a string value and treats the + operator as a concatenation operator. The final value that is assigned to the probablyConfusing variable is "345". Even though the string looks like a number, it is still a string. Any operation involving the + operator and a string results in a concatenation operation.

A string can be converted to a number using any other arithmetic operator. Look at the following example:

var probablyConfusing = "1" + 2 - 3;

In this code, the string "1" is concatenated with the numeric value 2. So this code can be simplified like this:

var probablyConfusing = "12" - 3;

The subtraction operation, however, is not a valid string operator. So JavaScript converts the string to a numeric value and performs the operation. The result of this code is 9, since "12" is converted to 12.

Converting Strings to Numbers

There are more ways to convert a string to a number, however. JavaScript provides two functions to convert strings to numbers: the parseInt() and parseFloat() functions. You'll learn much more about functions later, but for now all you need to know is that functions perform work on data.

Calling a function is as simple as using the function's identifier followed by a pair of parentheses, like this:

parseInt();

This executes the parseInt() function. However, it returns a value of NaN because it does not have any data to work with. Some functions, like parseInt(), accept data in the form of arguments, a set of special variables used by the function. For example, the parseInt() function accepts a string value to convert to a number, like this:

var num = parseInt("45");

This code converts the string "45" to the number 45 and stores it in the num variable. The parseInt() function returns an integer (a whole number) value. If a string containing a decimal number is passed to the parseInt() function, it drops the decimal and the numbers after it and returns the whole number. It does not round up. The following code demonstrates this:

num = parseInt("1.8392"); // returns 1

In this code, a string containing a decimal number is passed to the function. The result is the whole number: 1.

It is sometimes desirable to keep the numbers after the decimal. In cases such as these, use the parseFloat() function. An example is shown here:

var floatingNum = parseFloat("1.8392"); // returns 1.8392

In this code, the same string is passed to the parseFloat() function, and the result is the exact number passed to the function.

The parseInt() and parseFloat() functions parse the strings passed to them. They work by starting at the beginning of the string and look at each character in the string. The function determines if the character is a valid number. If it is, the function uses that numeric value to start building the number to return and looks at the next character. If the character isn't a number, JavaScript assumes the number has ended and stops parsing the string. This means that these two functions can parse strings that also contain alphabetical characters. The following code shows this:

var num = parseInt("1234abcd"); // returns 1234
var decNum = parseFloat("1.234abcd"); // returns 1.234
var num2 = parseInt("1234abcd5678"); // returns 1234

This code demonstrates how parseInt() and parseFloat() parse strings that contain alphabetical characters. In all three lines, the parsing functions begin parsing the strings with the first character, and they stop parsing when they encounter a non-numeric character. The third line demonstrates this better, since the string passed to parseInt() contains several numeric characters separated by a group of alphabetical characters.

The parseInt() function accepts an optional second argument called a radix. The radix determines what numeral system the string passed in the first argument is converted to. For example, we humans use a base 10 numeral system, but computers use a base 2 (binary) system. The binary number 100 is actually the base 10 number 4. When calling parseInt(), it's important to specify the radix; otherwise, JavaScript may interpret the string as a number of a different numeral system. So, if you want to convert a string to a number that we humans use, specify the radix of 10, like this:

var parsedNumber = parseInt("1043", 10); // 1043

Boolean

All computer systems use a binary system at their most basic level. The CPU and other processors are made up of transistors that are either turned on or turned off. The hard drive stores data by magnetically positively or negatively charging a tiny piece of the platter.

A bit is the simplest unit in a computer system. It can have only one of two states: It can either be turned on (1) or it can be turned off (0). In programming, the Boolean data type is typically the most basic data type, as it exactly represents the state of a bit. Boolean values are either true or false (on or off, respectively).

JavaScript has two Boolean literals: true and false. These values are different from the numeric equivalents of 1 and 0 even though they can be used to mean the same thing. You assign Boolean values like this:

var trueVar = true;
var falseVar = false;

Keep JavaScript's case-sensitivity in mind here. The true and false literal values are not the same as True and False, respectively.

Truthy and Falsy Values

JavaScript is somewhat unique in that true and false are not the only Boolean values in the language. In fact, all data types have values that are equivalent to true and false. JavaScript developers call these values truthy and falsy.

The Number data type's falsy values are the number zero (0) and NaN, , and all other numbers are considered truthy. The following code offers some examples of truthy and falsy number values:

var truthyVar = −56;
var truthyVar2 = 0.453;
var falseyVar = 0;
var falseyVar2 = 1 / 0;

The String data type follows along the same lines as numbers. An empty string ("") is a falsy value, whereas anything other than an empty string is a truthy value. The following lines of code show some examples:

truthyVar = " ";
truthyVar2 = "This is a string.";
falseyVar = "";

JavaScript has two more primitive data types, and they both serve as falsy values.

Undefined and Null

The Undefined and Null data types are special in JavaScript, primarily because they can have only one value each. The Undefined type's special value is called undefined, and Null's special value is null. Many beginning JavaScript developers think these two values are synonymous. On the contrary, these values serve two different purposes.

When a variable is declared, but not initialized, its value is said to be undefined. Recall from earlier in this chapter when you were first introduced to variables. The following code was used as an example:

var myVariable;
myVariable = "some text";

The first line declares the myVariable variable by using the var keyword followed by the variable's name. No value is assigned to it. Therefore, its value is undefined until another value is assigned to it.

The Null data type comes into play when you are dealing with objects. Later lessons will delve into objects, but for now, think of an object as a thing that contains multiple types of data. An empty object is said to be null. The value of null is best used to assign a value to a variable that will later hold an object. The following line of code assigns null to a variable:

var obj = null;

Don't worry about the Null data type right now. Later lessons will revisit null in the context of discussing objects, where it'll make much more sense.

Determining a Variable's Data Type

Before you work with data stored in variables, it's important to know what kind of data is actually stored within the variable. This isn't necessarily a problem in strongly-typed languages, as you generally know what type of data you're working with. Because of JavaScript's loosely-typed nature, however, it needs some way to identify a variable's data type. The typeof operator is used for this specific purpose.

The typeof operator is a unary operator, meaning it operates on only one operand. This is in contrast to the arithmetic and concatenation operators, which are binary operators (they perform operations on two operands). The typeof operator returns a string value containing the type of data stored in a variable. The following list displays the possible values:

  • "number": For number values

  • "string": For string values

  • "boolean": For Boolean values (pure Boolean values — not truthy or falsy values)

  • "undefined": For uninitialized variables

  • "object": For null

These are fairly self-explanatory, except for null. Remember that null refers to an empty object. Therefore, its data type is considered to be an object.

Look at the following code for an example:

var myVariable = 3.14;
var variableType = typeof myVariable; // "number"

The first line of code creates the myVariable variable and initializes it with a number value of 3.14. The second line uses the typeof operator against the myVariable operand to get the variable's data type. In this case, the typeof operator returns "number".

KEYWORDS AND RESERVED WORDS

Every programming language has a list of words that have specific uses. These are called keywords, and you've been introduced to several in this lesson. Keywords cannot be used as identifiers. The complete list of JavaScript's keywords is as follows:

break

case

catch

continue

default

delete

do

else

finally

for

function

if

in

instanceof

new

return

switch

this

throw

try

typeof

var

void

while

with

JavaScript also has a set of words that are reserved words. These are words that are not currently used in the language, but are reserved for future use. Following is the complete list of reserved words:

abstract

boolean

byte

char

class

const

debugger

double

enum

export

extends

final

float

goto

implements

import

int

interface

long

native

package

private

protected

public

short

static

super

synchronized

throws

transient

volatile

TRY IT

In this lesson, you learn about variables, primitive data types, and some of JavaScript's syntax.

Lesson Requirements

For this lesson, you need a text editor; any plain text editor will do. For Microsoft Windows users, Notepad is available by default on your system or you can download Microsoft's free Visual Web Developer Express (www.microsoft.com/express/web/) or Web Matrix (www.asp.net/webmatrix/). Mac OS X users can use TextMate, which comes as part of OS X, or they can download a trial for Coda (www.panic.com/coda/). Linux users can use the built-in VIM.

You also need a modern web browser. Choose any of the following:

  • Internet Explorer 8+

  • Google Chrome

  • Firefox 3.5+

  • Apple Safari 4+

  • Opera 10+

Create a subfolder called Lesson01 in the JS24Hour folder you created in Lesson 01. Store the files you create in this lesson in the Lesson02 folder.

Step-by-Step

Create and initialize three variables. The first variable should contain a numeric value. The second variable's initialization should use the value of the first variable in an addition operation. The third variable should contain a string followed by the numeric value in the second variable. Use the alert() function to display the string value in the third variable.

  1. Open your text editor, type the following code, and save the file as lesson02_sample01.js.

    var myVariable = 3;
    var myVariable2 = myVariable + 2;
    var myVariable3 = "The value is: " + myVariable2;
    alert(myVariable3); // alert the value
  2. Open another instance of your text editor, type the following HTML, and save it as lesson02_sample01.htm:

    <html>
    <head>
        <title>Sample Page</title>
    </head>
    <body>
        <script type="text/javascript" src="lesson02_sample01.js"></script>
    </body>
    </html>
  3. Open the HTML file in your browser. You will see an alert box displaying a value of "The value is: 5".

Note

Please select Lesson 2 on the DVD to view the video that accompanies this lesson. You can also download the sample code for all lessons from the book's website at www.wrox.com.

Step-by-Step
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.137.59