EXERCISE
1JavaScript does not lock a variable to one type. You can store a number, then replace it with a string, then replace it with a boolean. That is called a loosely typed (or weakly typed) language.
is loosely typed, which means a variable is not tied to a kind of value. The same name can hold a number, then a string, then an object, and nothing complains. The type belongs to the value, not to the variable.
var thing = 42;
console.log(typeof thing); // "number"
thing = "forty-two";
console.log(typeof thing); // "string"
thing = { value: 42 };
console.log(typeof thing); // "object"
The upside is obvious: less ceremony, fewer declarations, faster to write. The cost is that a wrong type is not caught when you write it, or when the file loads. It is caught when something finally tries to use the value, which can be much later and somewhere unrelated.
This is where undefined becomes genuinely dangerous rather than merely untidy, because it participates in operations instead of stopping them:
var price;
console.log(price + 10); // NaN
console.log("Total: " + price); // "Total: undefined"
console.log(price * 2); // NaN
None of those three lines throws. The first and third produce NaN, which then spreads through every calculation that touches it. The second produces a string that will be rendered to a user, on a page, in production, reading Total: undefined. The mistake happened wherever price was supposed to be set; the symptom appears wherever the value is finally used, and those two places can be in different files.
The habit worth forming is to check before you use, at the boundary where a value arrives:
function total(price, qty) {
if (typeof price !== "number" || typeof qty !== "number") {
throw new Error("total() needs two numbers");
}
return price * qty;
}
That turns a silent NaN that surfaces three functions later into a loud failure at the point the bad value entered. Loose typing is not a flaw to work around, but it does move the responsibility for type checking from the language to you, and the cheapest place to accept that responsibility is the edge of your own functions.