Data types
JavaScript values come in a handful of types. Seven are primitive (simple values), and everything else is an object.
| Type | Example |
|---|---|
number | 42, 3.14, -7, NaN |
string | "hello", 'hi', or a template literal in backticks |
boolean | true, false |
undefined | a variable with no value yet |
null | "intentionally empty" |
bigint | 123n, for huge integers |
symbol | unique identifiers (advanced) |
object | {}, [], functions, dates... |
typeof
JavaScript
console.log(typeof 42);
console.log(typeof "hi");
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof { a: 1 });
console.log(typeof [1, 2]); // arrays are objects
console.log(typeof null); // a famous historical bug: "object"One number type
JavaScript has a single number type for both whole numbers and decimals:
JavaScript
console.log(7 / 2);
console.log(0.1 + 0.2);
console.log(10 / 0);
console.log("abc" * 2); // NaN: "Not a Number"
console.log(Number.isNaN("abc" * 2));undefined vs null
undefinedmeans "no value has been given yet". JavaScript uses it automatically.nullmeans "deliberately empty". You set it yourself.
JavaScript
let notSetYet;
let emptyOnPurpose = null;
console.log(notSetYet, emptyOnPurpose);Type conversion and the == trap
JavaScript converts types automatically in some situations, and the results can be surprising:
JavaScript
console.log("5" + 3); // "53": + with a string joins
console.log("5" - 3); // 2: - converts to numbers
console.log("5" == 5); // true: == converts before comparing
console.log("5" === 5); // false: === compares type AND value
console.log(0 == ""); // true (!)
console.log(0 === ""); // falseConverting on purpose
JavaScript
console.log(Number("42"), Number("4.5"), Number("abc"));
console.log(parseInt("42px"), parseFloat("3.5kg"));
console.log(String(99), (99).toString());
console.log(Boolean(""), Boolean("hi"), Boolean(0));Finished this lesson?Mark it complete to earn +20 XP and move your progress on.