Skip to content
Sign inGet all access
Chapter 2·32 minFree

Types & Variables

The primitives, let/const/var, typeof null, and all the coercion rules.

let and const

Two declarations for new code. let can be reassigned, const cannot:

app.mjs
let count = 1
count = 2

const name = "ada"

console.log(count, name)
Output2 ada

Reassigning a const is an error:

app.mjs
const name = "ada"
name = "linus"
OutputTypeError: Assignment to constant variable.

But const freezes the binding, not the value. An object it points at is still mutable:

app.mjs
const user = { name: "ada" }
user.name = "linus"

console.log(user)
Output{ name: 'linus' }

Block scope

Both are scoped to the nearest { }, so an inner declaration shadows an outer one without touching it:

app.mjs
let x = "outer"

{
  let x = "inner"
  console.log(x)
}

console.log(x)
Outputinnerouter

var and hoisting

var is the third declaration — read it in old code, do not write it. It is scoped to the whole function:

app.mjs
function f() {
  if (true) {
    var a = "var leaks"
    let b = "let does not"
  }

  console.log(a)
  console.log(b)
}

f()
Outputvar leaksReferenceError: b is not defined

A var is also hoisted to the top of its function, so reading it early gives undefined rather than an error:

app.mjs
console.log(greeting)
var greeting = "hello"
Outputundefined

The temporal dead zone

A let or const is hoisted too, but reading it before its declaration throws. That gap is the temporal dead zone:

app.mjs
console.log(greeting)
let greeting = "hello"
OutputReferenceError: Cannot access 'greeting' before initialization

The primitive types

Seven of them, and typeof names each:

app.mjs
console.log(typeof "ada")
console.log(typeof 36)
console.log(typeof true)
console.log(typeof undefined)
console.log(typeof Symbol("id"))
console.log(typeof 10n)
Outputstringnumberbooleanundefinedsymbolbigint

The seventh is null. Everything else — objects, arrays, functions, dates — is an object.

typeof

Three of its answers are worth memorising because they are not what you expect:

app.mjs
console.log(typeof null)
console.log(typeof [1, 2])
console.log(typeof function () {})
Outputobjectobjectfunction

null vs undefined

undefined means nothing was assigned; null means someone assigned it deliberately. They are loosely equal to each other and nothing else:

app.mjs
let assigned = null
let never

console.log(assigned)
console.log(never)
console.log(assigned == never)
console.log(assigned === never)
Outputnullundefinedtruefalse

One number type

There is no int or float. Every number is a 64-bit float, so division never truncates and overflow produces Infinity rather than wrapping:

app.mjs
console.log(7 / 2)
console.log(Number.isInteger(10))
console.log(10 / 0)
console.log(-10 / 0)
Output3.5trueInfinity-Infinity

Floats cannot represent every decimal, which has one famous consequence:

app.mjs
console.log(0.1 + 0.2)
console.log(0.1 + 0.2 === 0.3)
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON)
Output0.30000000000000004falsetrue

Integers are exact only up to Number.MAX_SAFE_INTEGER. Past that, use BigInt:

app.mjs
console.log(Number.MAX_SAFE_INTEGER)
console.log(Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2)
console.log(9007199254740993n + 1n)
Output9007199254740991true9007199254740994n

NaN

“Not a Number” is itself a number, and it is the only value not equal to itself:

app.mjs
const result = Number("abc")

console.log(result)
console.log(result === result)
console.log(Number.isNaN(result))
console.log(Object.is(result, NaN))
OutputNaNfalsetruetrue

Use Number.isNaN, never the global isNaN, which converts its argument first:

app.mjs
console.log(isNaN("abc"))
console.log(Number.isNaN("abc"))
Outputtruefalse

Strings are immutable

No method changes a string in place. Writing to an index throws in a module:

app.mjs
const s = "ada"
s[0] = "X"
OutputTypeError: Cannot assign to read only property '0' of string 'ada'

Symbols

A unique value, used as a property key that cannot collide. Same description, still different:

app.mjs
const id = Symbol("id")
const other = Symbol("id")

console.log(id === other)
console.log(id.description)
Outputfalseid

Arithmetic operators

The familiar five, plus ** for exponentiation. / never truncates, and % keeps the sign of the left operand:

app.mjs
console.log(2 ** 10)
console.log(7 % 3)
console.log(-7 % 3)
console.log(7 / 2)
Output10241-13.5

++ and -- return a different value depending on which side they sit: n++ gives the value before incrementing, ++n the value after:

app.mjs
let n = 5

console.log(n++)
console.log(n)
console.log(++n)
Output567

Assignment operators

Every arithmetic operator has a compound form. Three logical ones assign only when the left side qualifies:

app.mjs
let total = 10
total += 5
total **= 2
console.log(total)

let name = null
name ??= "anonymous"
console.log(name)

let opts = { debug: false }
opts.debug ||= true
console.log(opts.debug)

let cfg = { mode: "dev" }
cfg.mode &&= cfg.mode.toUpperCase()
console.log(cfg.mode)
Output225anonymoustrueDEV

Comparison and logical operators

The six comparisons return booleans, but they do not chain the way maths does:

app.mjs
console.log(3 > 2 > 1)
console.log(1 < 2 < 3)
Outputfalsetrue

&& and || return one of their operands, not a boolean. !! is the idiom for forcing a real boolean:

app.mjs
console.log("ada" && 36)
console.log(0 || "fallback")
console.log(!!"text")
Output36fallbacktrue

The ternary is the only operator taking three operands, and is used far more in JavaScript than in most languages:

app.mjs
const age = 20

console.log(age >= 18 ? "adult" : "minor")
Outputadult

Bitwise operators

These convert their operands to 32-bit integers first, which makes them the one place a JavaScript number stops being a float:

app.mjs
console.log(5 & 3)
console.log(5 | 3)
console.log(5 ^ 3)
console.log(~5)
console.log(1 << 3)
console.log(-8 >> 1)
Output176-68-4

Precedence

Highest first. Within a row, evaluation runs left to right except where noted:

Operators Notes
() . ?. [] grouping and access
new
++ -- postfix
! ~ + - ++ -- typeof void delete prefix, unary
** right to left
* / %
+ -
<< >> >>>
< <= > >= in instanceof
== != === !==
&
^
|
&&
|| ?? cannot be mixed without parentheses
? : right to left
= += ??= and the rest right to left
,

Loose vs strict equality

=== compares type and value with no conversion; == converts first. Use === everywhere, with x == null as the one accepted exception:

app.mjs
console.log(1 === 1)
console.log("1" === 1)
console.log("1" == 1)
Outputtruefalsetrue

The coercion table

When an operator meets two different types it converts one of them. + prefers strings if either side is one; every other arithmetic operator prefers numbers:

app.mjs
console.log("1" + 1)
console.log("3" * 2)
console.log(null + 1)
console.log(undefined + 1)
console.log([] + {})
console.log(true + 1)
Output1161NaN[object Object]2

Truthiness

Every value is either truthy or falsy. There are exactly eight falsy values, and this checks that none of them survives a Boolean conversion:

app.mjs
const falsy = [false, 0, -0, 0n, "", null, undefined, NaN]

console.log(falsy.some(Boolean))
console.log(Boolean("0"), Boolean([]), Boolean({}))
Outputfalsetrue true true

Falsy vs nullish fallback

|| falls back on any falsy value, ?? only on null and undefined. JSON.stringify here makes the surviving empty string visible:

app.mjs
const count = 0
const label = ""

console.log(count || 10)
console.log(count ?? 10)
console.log(label || "none")
console.log(JSON.stringify(label ?? "none"))
Output100none""

Optional chaining

?. returns undefined the moment the left side is null or undefined, and short-circuits the rest of the chain:

app.mjs
const user = { name: "ada", address: null }

console.log(user.address?.city)
console.log(user.missing?.deep?.deeper)
console.log(user.greet?.())
Outputundefinedundefinedundefined

Without it, the same read throws:

app.mjs
const user = { address: null }

console.log(user.address.city)
OutputTypeError: Cannot read properties of null (reading 'city')

Converting on purpose

The three constructors convert without surprises, returning NaN rather than guessing:

app.mjs
console.log(Number("42"))
console.log(Number(""))
console.log(Number("42abc"))
console.log(String(42))
console.log(Boolean(""))
Output420NaN42false

parseInt is the looser alternative: it reads as far as it can and stops:

app.mjs
console.log(parseInt("42abc"))
console.log(parseInt("08"))
console.log(parseInt("0x1f"))
console.log(parseInt("08", 10))
console.log(Number("42abc"))
Output428318NaN

A leading unary + is the shorthand for Number(), with identical results:

app.mjs
console.log(+"42")
console.log(+"3.14")
console.log(+"")
console.log(+"42abc")
Output423.140NaN

It is the same + that concatenates, so where it sits decides what you get:

app.mjs
const count = "5"

console.log(count + 1)
console.log(+count + 1)
Output516

Comparing objects

Objects compare by identity, never by contents. Two objects with identical fields are not equal:

app.mjs
const a = { id: 1 }
const b = { id: 1 }
const c = a

console.log(a === b)
console.log(a === c)
console.log(JSON.stringify(a) === JSON.stringify(b))
Outputfalsetruetrue