Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Q&A

Q1:

What happens if I compare two items of different data types (for example, a number and a string) in a conditional expression?

A1:

The JavaScript interpreter does its best to make the values a common format and compare them. In this case, it would convert them both to strings before comparing. In JavaScript 1.3 and later, you can use the special equality operator === to compare two values and their types—using this operator, the expression will be true only if the expressions have the same value and the same data type.

Q2:

Why don't I get a friendly error message if I accidentally use = instead of == ?

A2:

In some cases, this will result in an error. However, the incorrect version often appears to be a correct statement. For example, in the statement if (a=1), the variable a will be assigned the value 1. The if statement is considered true, and the value of a is lost.

Q3:

Why does the script in Listing 6.1 specify JavaScript 1.2?

A3:

The switch statement was added in JavaScript 1.2. Specifying that version prevents older browsers from attempting to execute the script and becoming confused.

Share ThisShare This

Informit Network