Coding Hub  /  Reference

javascript basics

Variables, operators, arrays, array methods, loops. The pieces you use in every program, in one place. Every example can be run and edited in the scratchpad below.

scratchpad — nums = [5, 3, 8, 1, 9, 2]  ·  words = ['pear', 'fig', 'apple', 'date']

  

Part one: values and operators

Where the surprises live. Most "impossible" bugs in a first year trace back to one of these seven entries.

01 let, const, var

Use const by default. Switch to let only when you genuinely reassign. Never write var in new code.

const means the name cannot be pointed at something else. It does not freeze the value. A const array can still be pushed to — that is why most arrays are declared const and still change.

the three
Reassign?ScopeUse
constnothe blockDefault. Almost everything.
letyesthe blockCounters, accumulators, anything that changes
varyesthe whole functionLegacy. Leaks out of blocks.
const is about the name
const total = 5
total = 6              // TypeError: Assignment to constant variable

const scores = [1, 2]
scores.push(3)         // fine — the array changed, the name did not
scores = [9]           // TypeError again

02 Types and typeof

Seven types you will meet, plus the two famous oddities at the bottom of the table.

typeof null returning 'object' is a bug from 1995 that can never be fixed without breaking the web. To test for an array, use Array.isArray(x) — typeof will not help you.

typeof
ValuetypeofNote
'hello''string'
42, 3.14, NaN'number'One number type. No separate int.
true'boolean'
undefined'undefined'Declared, never given a value
{ a: 1 }'object'
function(){}'function'
Symbol()'symbol'Rare in everyday code
null'object'A famous mistake. Test with x === null.
[1, 2]'object'Test with Array.isArray()
undefined vs null
let a                  // undefined — nobody has set it yet
const b = null         // null — deliberately set to "nothing"

// NaN is a number that means "not a valid number"
Number('abc')          // NaN
NaN === NaN            // false (!) — use Number.isNaN(x)

03 Arithmetic

Nothing surprising except +, which both adds numbers and joins strings. One string anywhere in the expression and the whole thing becomes text.

This is why a form value needs Number(...) before arithmetic. Everything from an input, a URL or a query string arrives as a string, so '5' + 1 is '51'.

operators
OperatorDoesExample
+ - * /the usual7 / 2 → 3.5
%remainder7 % 2 → 1. Even test: n % 2 === 0
**power2 ** 10 → 1024
++ --add or subtract onecount++
+= -= *= /=change in placetotal += 5
the + problem
2 + 3                  // 5
'2' + 3                // '23'   <- a string got in
'2' * 3                // 6      <- only + joins; the others convert

Number('2') + 3        // 5      <- convert first, every time
parseInt('42px', 10)   // 42     <- stops at the first non-digit

04 == versus ===

Use ===. Always. It compares value and type, and it never surprises you.

== converts the two sides to a common type before comparing, by rules nobody remembers correctly. The results in the table are all real.

The one accepted use of == is x == null, which is true for both null and undefined. Even then, many teams ban it and write the check out in full.

why ===
Expression=====
1 == '1'truefalse
0 == ''truefalse
0 == falsetruefalse
null == undefinedtruefalse
[] == falsetruefalse
'' == '0'falsefalse

05 Truthy and falsy

Anywhere JavaScript wants a yes or no — an if, a &&, a while — a non-boolean gets treated as one.

There are exactly eight falsy values. Memorise the list; everything else in the language is truthy, including [], {}, '0' and 'false'.

The classic bug: if (count) is false when count is 0, which is usually a real value you wanted to keep. Write if (count !== undefined) when zero is legitimate.

the complete falsy list
false
0
-0
0n            // BigInt zero
''            // empty string
null
undefined
NaN

// Everything else is truthy. Including these, which trip people up:
[]            // truthy — an empty array is still an array
{}            // truthy
'0'           // truthy — a non-empty string
'false'       // truthy
function(){}  // truthy

06 Logical operators

&& and || do not return true or false. They return one of the operands, which is what makes the "default value" pattern work.

?? is the fix for ||'s weakness: it only falls back on null and undefined, so a legitimate 0 or '' survives.

?. stops the whole expression and gives undefined rather than throwing when something in the chain is missing.

operators
OperatorReturns
a && ba if it is falsy, otherwise b
a || ba if it is truthy, otherwise b
a ?? bb only when a is null or undefined
!athe opposite, always a real boolean
a?.bundefined if a is null or undefined, instead of throwing
|| versus ??
const limit = input || 20      // 0 becomes 20  <- probably a bug
const limit = input ?? 20      // 0 stays 0     <- probably what you meant

// Optional chaining, for data that might not be there
user?.address?.city            // undefined rather than a TypeError
req.body?.name                 // handy when the body may be missing

07 Ternary and templates

The ternary is an if that produces a value, so it can sit inside an assignment or a template.

Template literals use backticks and ${ }. They beat + joining for anything with more than one slot, and they can span lines.

Do not nest ternaries more than one deep. A nested ternary is unreadable within a week — use an if.

both
// condition ? valueIfTrue : valueIfFalse
const label = count === 1 ? 'item' : 'items'

// Template literal — backticks, not quotes
console.log(`You have ${count} ${label}`)

// Any expression fits inside ${ }
console.log(`Total: ${price * quantity}`)
console.log(`${user.name} is ${user.age >= 18 ? 'an adult' : 'a minor'}`)

Part two: arrays

Run everything here in the scratchpad at the top of the page. It tells you whether the original array survived.

08 Making and reading arrays

Positions start at zero, so the last index is always length - 1.

A negative index is not an error, it is just a miss: arr[-1] gives undefined. Use arr.at(-1) for the last item.

basics
const nums = [5, 3, 8, 1, 9, 2]

nums[0]           // 5     first
nums[2]           // 8
nums.length       // 6
nums[nums.length - 1]   // 2   last, the long way
nums.at(-1)       // 2        last, the short way
nums[99]          // undefined — no error, just nothing there

nums[1] = 30      // replace in place
Array.isArray(nums)     // true

09 Adding and removing

These four all change the original array. Two work at the end, two at the front.

Working at the front costs more than working at the end, because every remaining item has to shift along. With a handful of items it does not matter; with a hundred thousand, it does.

all four mutate
MethodDoesReturns
push(x)add to the endthe new length
pop()remove from the endthe removed item
unshift(x)add to the frontthe new length
shift()remove from the frontthe removed item
splice(i, n)remove n items from index ithe removed items
splice(i, 0, x)insert x at index i[]
push returns a length, not the array
const nums = [5, 3, 8]

const result = nums.push(7)
result            // 4  <- the new LENGTH, a common surprise
nums              // [5, 3, 8, 7]

nums.pop()        // 7  <- the item itself
nums              // [5, 3, 8]

10 Copying and slicing

slice takes a piece and leaves the original alone. splice cuts a piece out and changes it. One letter apart, opposite behaviour — this is the single most common array mix-up.

Assigning an array does not copy it: const b = a makes a second name for the same array, so changing b changes a. Use the spread operator to get a real copy.

copies and pieces
const nums = [5, 3, 8, 1, 9]

nums.slice(1, 3)       // [3, 8]   from 1 up to but not including 3
nums.slice(2)          // [8, 1, 9]
nums.slice(-2)         // [1, 9]   a negative start counts from the end
nums                   // unchanged

const copy = [...nums]           // a real copy
const joined = [...nums, 100]    // copy plus one
const merged = [...a, ...b]      // concat, written with spread

const alias = nums               // NOT a copy — same array, two names
alias.push(0)
nums                             // also has the 0

11 Searching an array

Four methods, and which one you want depends on whether you need a yes/no, a position, or the item.

find returns undefined when nothing matches, but findIndex and indexOf return -1. Checking if (index) after an indexOf is wrong twice over: -1 is truthy, and a real match at position 0 is falsy.

searching
MethodAnswersIf nothing matches
includes(x)is it in there?false
indexOf(x)at what position?-1
find(fn)the first item that passesundefined
findIndex(fn)the position of the first that passes-1
the -1 trap
const i = nums.indexOf(99)
if (i) { }              // WRONG — -1 is truthy
if (i !== -1) { }       // right

const user = users.find(u => u.id === 3)
if (!user) return null  // find gives undefined, so check for that

12 map, filter, reduce

The three that replace most loops. None of them touch the original array; each returns something new.

map gives an array of the same length with every item transformed. filter gives a shorter array of the items that passed a test. reduce boils the whole array down to one value.

Inside map, a { after the arrow starts a function body, so you need an explicit return. Forget it and you get an array of undefined.

the three
const nums = [5, 3, 8, 1, 9, 2]

// map — same length, each item changed
nums.map(n => n * 2)                 // [10, 6, 16, 2, 18, 4]

// filter — only the ones that pass
nums.filter(n => n > 4)              // [5, 8, 9]

// reduce — everything down to one value.
// (runningTotal, currentItem) and a starting value.
nums.reduce((total, n) => total + n, 0)     // 28
nums.reduce((max, n) => n > max ? n : max)  // 9  (no start value: uses item 0)
the missing return
nums.map(n => n * 2)            // [10, 6, ...]  implicit return
nums.map(n => { n * 2 })        // [undefined, undefined, ...]
nums.map(n => { return n * 2 }) // [10, 6, ...]  explicit, correct

// Returning an object needs parentheses, or the { looks like a body
users.map(u => ({ id: u.id }))

13 some, every, chaining

some asks whether at least one item passes; every asks whether all of them do. Both return a real boolean and both stop early once the answer is settled.

Because map and filter each return an array, they chain. Read a chain left to right as a sentence.

tests and chains
nums.some(n => n > 8)        // true  — at least one
nums.every(n => n > 0)       // true  — all of them

// Chaining: filter first to do less work in the steps after it
const total = books
  .filter(b => b.inStock)
  .map(b => b.price)
  .reduce((sum, p) => sum + p, 0)

// every on an empty array is true, some is false. Both are
// correct and both have surprised people at 2am.
[].every(n => n > 100)       // true
[].some(n => n > 100)        // false

14 sort, and the trap

With no arguments, sort converts every item to a string and sorts alphabetically. So [10, 9, 100].sort() gives [10, 100, 9]. It is not broken; it is doing exactly what it says.

For numbers, pass a compare function. It should return a negative number when a comes first, positive when b does, zero when the order does not matter — and a - b does all three at once.

sort also mutates. Spread first if you need the original order kept.

sorting
[10, 9, 100].sort()                 // [10, 100, 9]   alphabetical!
[10, 9, 100].sort((a, b) => a - b)  // [9, 10, 100]   ascending
[10, 9, 100].sort((a, b) => b - a)  // [100, 10, 9]   descending

// Strings sort sensibly without a function, but capitals come first
['pear', 'Fig', 'apple'].sort()     // ['Fig', 'apple', 'pear']
['pear', 'Fig', 'apple'].sort((a, b) => a.localeCompare(b))

// By a field
books.sort((a, b) => a.year - b.year)
books.sort((a, b) => a.title.localeCompare(b.title))

// Keep the original
const sorted = [...nums].sort((a, b) => a - b)

15 Mutating or not

The table worth pinning up. Knowing which column a method is in explains most array bugs.

Try any of them in the scratchpad: it reports whether nums changed.

the master table
MethodOriginalGives you
push popchangedlength / the item
shift unshiftchangedthe item / length
splicechangedthe removed items
sort reversechangedthe same array
fillchangedthe same array
slicesafea new array
concatsafea new array
map filtersafea new array
reducesafeone value
find findIndexsafean item / an index
includes indexOfsafeboolean / index
some everysafea boolean
joinsafea string
flatsafea new array
toSorted toReversedsafea new array (newer JS)

Part three: loops

Four ways to repeat, and one rule for choosing between them.

16 The four loops

A classic for when you need the index or you are counting. for...of for walking an array. while when you do not know in advance how many times. do...while when the body must run at least once.

A while whose condition never becomes false freezes the tab. If the page stops responding while you are testing a loop, that is what happened — close it and look at what is supposed to change the condition.

all four
// for — three parts: start, keep going while, after each pass
for (let i = 0; i < nums.length; i++) {
  console.log(i, nums[i])
}

// for...of — the values, no index bookkeeping
for (const n of nums) {
  console.log(n)
}

// while — condition checked before each pass
let i = 0
while (i < nums.length) {
  console.log(nums[i])
  i++                       // forget this and the tab freezes
}

// do...while — body first, then the check. Runs at least once.
let guess
do {
  guess = nextGuess()
} while (!isCorrect(guess))

17 for...of vs for...in

One letter apart, and they do genuinely different things.

for...of walks the values of an array. for...in walks the keys of an object — and on an array those keys are the indexes, delivered as strings.

Rule of thumb: of for arrays, in for objects. If you want the index of an array too, use entries().

the difference
const letters = ['a', 'b', 'c']

for (const x of letters) console.log(x)    // 'a'  'b'  'c'
for (const x in letters) console.log(x)    // '0'  '1'  '2'   strings!

'0' + 1                                     // '01'  <- the bug this causes

// Both at once
for (const [i, letter] of letters.entries()) {
  console.log(i, letter)                    // 0 'a'   1 'b'   2 'c'
}

// for...in is for objects
const book = { title: 'Dune', year: 1965 }
for (const key in book) console.log(key, book[key])

18 forEach cannot break

forEach runs a function once per item. It reads nicely, but it has two limits that matter.

You cannot break out of it — return inside only ends that one call, like continue. And it does not wait for await, so an async callback inside forEach fires everything off at once and moves on immediately.

When you might need to stop early, or you are awaiting anything, use for...of. It handles both.

when forEach is wrong
// Cannot stop early
nums.forEach(n => {
  if (n > 5) break      // SyntaxError: Illegal break statement
})

for (const n of nums) {
  if (n > 5) break      // works
}

// Does not wait
items.forEach(async (item) => {
  await save(item)      // all start at once; the loop is already done
})

for (const item of items) {
  await save(item)      // one after another, properly awaited
}

Part four: objects and functions

Enough to read the rest of the code you will meet this year.

19 Objects and destructuring

An object is named values. Reach them with a dot, or with brackets when the key is in a variable.

Destructuring pulls several properties out in one line, with defaults if they are missing. You will see it at the top of nearly every function that takes an options object.

objects
const book = { title: 'Dune', year: 1965, tags: ['classic'] }

book.title                 // 'Dune'
book['title']              // same thing
const key = 'year'
book[key]                  // 1965  <- brackets when the key is a variable

book.pages = 412           // add
delete book.tags           // remove

Object.keys(book)          // ['title', 'year', 'pages']
Object.values(book)        // ['Dune', 1965, 412]
Object.entries(book)       // [['title','Dune'], ...]
destructuring
const { title, year } = book            // two variables, one line
const { pages = 0 } = book              // with a default if missing
const { title: name } = book            // renamed to `name`

const [first, second] = nums            // arrays too

// The pattern you will see everywhere in Express
const { page = 1, limit = 20 } = req.query

// Spread, to copy an object with a change
const updated = { ...book, year: 1966 }

20 Functions and arrows

Three ways to write one. Arrow functions are shortest and are what you pass to map, filter and the rest.

Arrows have no this of their own. That is usually convenient, and it is exactly why a Mongoose schema method must use function — an arrow there leaves this.title undefined and the method silently does nothing.

three ways
// Declaration — hoisted, usable before it is defined
function double(n) { return n * 2 }

// Expression
const double = function (n) { return n * 2 }

// Arrow — one expression, implicit return
const double = n => n * 2

// Arrow with a body needs an explicit return
const double = (n) => {
  return n * 2
}

// Default values, and the rest operator
function greet(name = 'friend') { return `Hi ${name}` }
function sum(...numbers) { return numbers.reduce((a, b) => a + b, 0) }
sum(1, 2, 3)        // 6