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:
let count = 1
count = 2
const name = "ada"
console.log(count, name)Reassigning a const is an error:
const name = "ada"
name = "linus"But const freezes the binding, not the value. An object it points at is still mutable:
const user = { name: "ada" }
user.name = "linus"
console.log(user)Block scope
Both are scoped to the nearest { }, so an inner declaration shadows an outer one
without touching it:
let x = "outer"
{
let x = "inner"
console.log(x)
}
console.log(x)var and hoisting
var is the third declaration — read it in old code, do not write it. It is scoped to
the whole function:
function f() {
if (true) {
var a = "var leaks"
let b = "let does not"
}
console.log(a)
console.log(b)
}
f()A var is also hoisted to the top of its function, so reading it early gives
undefined rather than an error:
console.log(greeting)
var greeting = "hello"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:
console.log(greeting)
let greeting = "hello"The primitive types
Seven of them, and typeof names each:
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)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:
console.log(typeof null)
console.log(typeof [1, 2])
console.log(typeof function () {})null vs undefined
undefined means nothing was assigned; null means someone assigned it deliberately.
They are loosely equal to each other and nothing else:
let assigned = null
let never
console.log(assigned)
console.log(never)
console.log(assigned == never)
console.log(assigned === never)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:
console.log(7 / 2)
console.log(Number.isInteger(10))
console.log(10 / 0)
console.log(-10 / 0)Floats cannot represent every decimal, which has one famous consequence:
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)Integers are exact only up to Number.MAX_SAFE_INTEGER. Past that, use BigInt:
console.log(Number.MAX_SAFE_INTEGER)
console.log(Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2)
console.log(9007199254740993n + 1n)NaN
“Not a Number” is itself a number, and it is the only value not equal to itself:
const result = Number("abc")
console.log(result)
console.log(result === result)
console.log(Number.isNaN(result))
console.log(Object.is(result, NaN))Use Number.isNaN, never the global isNaN, which converts its argument first:
console.log(isNaN("abc"))
console.log(Number.isNaN("abc"))Strings are immutable
No method changes a string in place. Writing to an index throws in a module:
const s = "ada"
s[0] = "X"Symbols
A unique value, used as a property key that cannot collide. Same description, still different:
const id = Symbol("id")
const other = Symbol("id")
console.log(id === other)
console.log(id.description)Arithmetic operators
The familiar five, plus ** for exponentiation. / never truncates, and % keeps the
sign of the left operand:
console.log(2 ** 10)
console.log(7 % 3)
console.log(-7 % 3)
console.log(7 / 2)++ and -- return a different value depending on which side they sit: n++ gives the
value before incrementing, ++n the value after:
let n = 5
console.log(n++)
console.log(n)
console.log(++n)Assignment operators
Every arithmetic operator has a compound form. Three logical ones assign only when the left side qualifies:
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)Comparison and logical operators
The six comparisons return booleans, but they do not chain the way maths does:
console.log(3 > 2 > 1)
console.log(1 < 2 < 3)&& and || return one of their operands, not a boolean. !! is the idiom for
forcing a real boolean:
console.log("ada" && 36)
console.log(0 || "fallback")
console.log(!!"text")The ternary is the only operator taking three operands, and is used far more in JavaScript than in most languages:
const age = 20
console.log(age >= 18 ? "adult" : "minor")Bitwise operators
These convert their operands to 32-bit integers first, which makes them the one place a JavaScript number stops being a float:
console.log(5 & 3)
console.log(5 | 3)
console.log(5 ^ 3)
console.log(~5)
console.log(1 << 3)
console.log(-8 >> 1)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:
console.log(1 === 1)
console.log("1" === 1)
console.log("1" == 1)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:
console.log("1" + 1)
console.log("3" * 2)
console.log(null + 1)
console.log(undefined + 1)
console.log([] + {})
console.log(true + 1)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:
const falsy = [false, 0, -0, 0n, "", null, undefined, NaN]
console.log(falsy.some(Boolean))
console.log(Boolean("0"), Boolean([]), Boolean({}))Falsy vs nullish fallback
|| falls back on any falsy value, ?? only on null and undefined. JSON.stringify
here makes the surviving empty string visible:
const count = 0
const label = ""
console.log(count || 10)
console.log(count ?? 10)
console.log(label || "none")
console.log(JSON.stringify(label ?? "none"))Optional chaining
?. returns undefined the moment the left side is null or undefined, and
short-circuits the rest of the chain:
const user = { name: "ada", address: null }
console.log(user.address?.city)
console.log(user.missing?.deep?.deeper)
console.log(user.greet?.())Without it, the same read throws:
const user = { address: null }
console.log(user.address.city)Converting on purpose
The three constructors convert without surprises, returning NaN rather than guessing:
console.log(Number("42"))
console.log(Number(""))
console.log(Number("42abc"))
console.log(String(42))
console.log(Boolean(""))parseInt is the looser alternative: it reads as far as it can and stops:
console.log(parseInt("42abc"))
console.log(parseInt("08"))
console.log(parseInt("0x1f"))
console.log(parseInt("08", 10))
console.log(Number("42abc"))A leading unary + is the shorthand for Number(), with identical results:
console.log(+"42")
console.log(+"3.14")
console.log(+"")
console.log(+"42abc")It is the same + that concatenates, so where it sits decides what you get:
const count = "5"
console.log(count + 1)
console.log(+count + 1)Comparing objects
Objects compare by identity, never by contents. Two objects with identical fields are not equal:
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))