Values and types

JavaScript · Essentials · 10 min

Every bug about unexpected comparisons or 'undefined is not a function' starts with not knowing what type a value has.

JavaScript is dynamically typed: variables don't have types, values do. Every value is either an object or one of seven primitives:

  • string — text, "hi"
  • number — 64-bit floating point, 42, 3.14, NaN
  • bigint — arbitrary-size integers, 10n
  • boolean — true / false
  • undefined — "no value assigned"
  • null — "intentionally empty"
  • symbol — unique identifiers

Everything else — arrays, functions, dates, plain {} — is an object.

Primitives are immutable and compared by value: "a" === "a" is true. Objects are compared by reference: two separate {} are never equal, even with identical contents.

typeof tells you the type as a string. It has two famous quirks: typeof null is "object" (a bug kept for compatibility) and typeof of a function is "function". Use Array.isArray(x) for arrays and x === null for null.

When a value is used as a condition, it is converted to a boolean. Exactly these values are falsy: false, 0, -0, 0n, "", null, undefined and NaN. Everything else is truthy — including "0", "false", [] and {}.

Calling a method on a primitive, as in "abc".toUpperCase(), works because the engine temporarily wraps it in an object (String). You never need new String() yourself.

Example

console.log(typeof "hi");        // "string"
console.log(typeof 42);          // "number"
console.log(typeof 42n);         // "bigint"
console.log(typeof undefined);   // "undefined"
console.log(typeof null);        // "object"  (historic quirk)
console.log(typeof [1, 2]);      // "object"
console.log(typeof (() => {}));  // "function"
console.log(Array.isArray([1])); // true

console.log({} === {});          // false: different objects
console.log(Boolean(""), Boolean("0"), Boolean([])); // false true true

Remember

  • Seven primitives plus objects; primitives compare by value, objects by reference
  • Falsy: false, 0, -0, 0n, "", null, undefined, NaN — everything else is truthy
  • typeof null === "object"; test arrays with Array.isArray

Watch out for

  • Assuming an empty array or object is falsy — if ([]) runs its body.

Check yourself

  1. What does typeof null return?
  2. Which of these values is truthy?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Data_structures