Dynamic typing
In JavaScript, the value has a type, not the variable. A variable can hold a number now and text later. That is called dynamic typing.
let thing = 42;
console.log(typeof thing); // → number
thing = "now I am text";
console.log(typeof thing); // → string
thing = true;
console.log(typeof thing); // → boolean
This is flexible, but it also means mistakes show up when the code runs rather than before. Careful names and checks help, and tools such as TypeScript add type checking on top of JavaScript if you need it later.
typeof
typeof returns the type of a value as a string.
console.log(typeof "hi"); // → string
console.log(typeof 5); // → number
console.log(typeof 5n); // → bigint
console.log(typeof true); // → boolean
console.log(typeof undefined); // → undefined
console.log(typeof Symbol()); // → symbol
console.log(typeof {}); // → object
console.log(typeof [1, 2]); // → object
console.log(typeof function () {}); // → function
console.log(typeof null); // → object
The quirks
typeof nullis"object"(a historical bug).typeof []is"object". To check for an array, useArray.isArray(value).typeof NaNis"number".NaNmeans “not a number” but it still belongs to the number type.- A function has its own result,
"function", even though functions are objects.
console.log(Array.isArray([1, 2])); // → true
console.log(Array.isArray({})); // → false
console.log(typeof NaN); // → number
typeof never fails on missing variables
console.log(typeof notDeclaredAnywhere); // → undefined
It returns "undefined" instead of throwing, which makes it handy for checking whether a global exists.
Type conversion
"5" + 1. This can be surprising. Arithmetic Operators and Strict vs Loose Equality show where it matters.