Type Conversion and Equality

JavaScript is called a loosely typed language because any variable or property can contain any type of data, but this flexibility doesn't come free. Every piece of data still has a type, and there are several situations where decisions need to be made about how to handle those types. To save the script writer the overhead of making those decisions (typical of a strongly typed language), the JavaScript interpreter follows a set of built-in rules. Obscure and hard to find bugs can occur if these rules aren't appreciated by the script writer. Generally speaking, the only time these rules apply is when type conversion happens—a piece of data of a given type needs to turn into another type. Some examples of when this might happen are:

var u = String(5.35);            // 5.35 or "5.35" ?
var v = "10" + 23;               // "1023" or 33 ?
var w = ( "10.5" ==  10.5 );         // true or false ?
var x = new Object;
var y = x + 1;               // what ?

© 1997 by Wrox Press. All rights reserved.