Dynamic Typing and typeof
A variable in JavaScript can hold any type and can change type at any moment, which is both the language's convenience and its trap.
Types belong to values, not to variables, so the same name can hold a string then a number. typeof reports the type at that instant, with two known lies: null reports object and a function reports function.
EXERCISE
1The Variable Does Not Have a Type, the Value Does
In many languages a variable is declared with a type and keeps it forever, and JavaScript works the other way round.
is dynamically typed. You never write a type, and the same variable can hold different types over its life.
Perfectly legal, and it runs:
let thing = "hello";
console.log(typeof thing); // string
thing = 42;
console.log(typeof thing); // number
thing = true;
console.log(typeof thing); // boolean
thing = { a: 1 };
console.log(typeof thing); // object
Compare with a statically typed language:
// In Java or C# you would write something like:
// String thing = "hello";
// thing = 42; <- refused before the program even runs
// JavaScript refuses nothing. It finds out at the moment it runs
// the line, which is why the errors arrive later and in production.
The freedom and the cost in one example:
function describe(value) {
return `${value} is a ${typeof value}`;
}
// One function, any type. That is the freedom.
console.log(describe("hi")); // hi is a string
console.log(describe(42)); // 42 is a number
console.log(describe(true)); // true is a boolean
// And the cost: nothing stopped this from being called wrongly.
function double(n) {
return n * 2;
}
console.log(double("5")); // 10 it worked by accident
console.log(double("abc")); // NaN no error, just a wrong answer
Dynamic typing means mistakes surface when the line runs, not when you write it. That is why the habits in this course matter so much: converting at the boundary, naming values for what they hold, and checking types when input comes from outside your program. exists to move these errors back to writing time, and it is a natural next step after this course.
EXERCISE
2typeof and Its Two Famous Lies
typeof tells you the type of any value in one word, and you need to know the two cases where the word it gives you is wrong.
typeof takes a value and returns a string naming its type.
The honest answers:
console.log(typeof "hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof { a: 1 }); // "object"
console.log(typeof Symbol()); // "symbol"
console.log(typeof 10n); // "bigint"
Lie number one, from 1995:
console.log(typeof null); // "object"
// null is its own type. This was a bug in the very first
// implementation and fixing it would break too much existing code.
// Check for it directly instead:
const value = null;
console.log(value === null); // true
Lie number two, which is more of a convenience:
console.log(typeof function () {}); // "function"
// A function IS an object. typeof singles it out because
// "is this callable?" is a question worth answering quickly.
// Useful, so nobody complains about this one.
And the gap it leaves:
console.log(typeof [1, 2, 3]); // "object" not "array"
console.log(typeof new Date()); // "object" not "date"
// For arrays there is a dedicated check:
console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray({ a: 1 })); // false
Pro Tip:
typeofis good at telling primitives apart and poor at telling objects apart, because almost everything that is not a primitive answers"object". Usetypeoffor primitives,Array.isArrayfor arrays, and a direct=== nullcomparison for null. Those three cover essentially everything you will need.
EXERCISE
3Coercion: When JavaScript Converts Behind Your Back
The language will quietly change a value's type to make an operation work, which is convenient about half of the time.
Coercion is automatic type conversion. It is why "5" * 2 is 10 and why "5" + 2 is "52".
The plus operator is the odd one out:
// + means "join" if either side is a string, otherwise "add"
console.log("5" + 2); // "52" joined
console.log(5 + "2"); // "52" joined
console.log("5" + true); // "5true"
// Every other arithmetic operator converts to number
console.log("5" - 2); // 3
console.log("5" * 2); // 10
console.log("10" / "2"); // 5
console.log("5" % 2); // 1
Comparison coerces too, which is why == is avoided:
console.log(1 == "1"); // true converts, then compares
console.log(1 === "1"); // false compares type as well
console.log(0 == false); // true
console.log("" == false); // true
console.log(null == 0); // false <- and this one has no good reason
// === never converts. That is the entire difference,
// and it is why === is the one to use.
Converting on purpose instead:
const typed = "5";
console.log(Number(typed) + 2); // 7 explicit
console.log(String(42) + "!"); // "42!" explicit
console.log(Boolean("")); // false explicit
// Reads clearly, behaves predictably, and the next person
// does not have to remember a coercion table.
Pro Tip: Use
===always and convert types yourself. Coercion is not evil, but its rules have enough exceptions that nobody remembers all of them, and code that relies on them is code whose behaviour depends on trivia. Explicit conversion costs six characters and removes the guesswork permanently.
