Lesson 5 · Web development foundations

JavaScript essentials

Values, arrays, objects and functions: the language you will use every day.

About 35 minutes

Tab indents. Press Escape, then Tab, to leave the editor.

JavaScript is the only programming language every web browser runs, which makes it the language of interactive web pages. It also runs on servers (with Node.js and similar runtimes), in mobile apps built with React Native, and in desktop apps. Most professional teams now write TypeScript, which is JavaScript plus type annotations that are checked before the code runs, but TypeScript compiles to JavaScript and everything in this lesson applies to it directly. This lesson covers the parts you'll use every working day: values, variables, arrays, objects and functions.

Values and their types

Every piece of data in JavaScript is a value, and every value has a type:

TypeExamplesUsed for
number42, 3.5, -1counts, sizes, money in cents
string'Water', "4 litres"text
booleantrue, falseyes/no decisions
nullnull"deliberately empty"
undefinedundefined"nothing was ever set"
object{ name: 'Rice' }, [1, 2, 3]grouping values together (arrays are objects too)

You can check a value's type with typeof: typeof 42 is 'number'. (One famous quirk: typeof null is 'object', a bug from 1995 that can't be fixed without breaking old websites.)

Numbers are stored as 64-bit floating point, which can't represent most decimal fractions exactly. That's why 0.1 + 0.2 is 0.30000000000000004. It's not a JavaScript bug; most languages behave the same way. The practical rule: store money as whole numbers of the smallest unit, such as cents, and only format it as dollars when you show it.

Variables: const and let

A variable is a name for a value.

const city = 'Lima'      // can't be reassigned
let bottles = 3          // can be reassigned
bottles = bottles + 1

Use const by default and let only when you need to reassign. That way, a reader knows any let will change. You'll still see var in older code; it has confusing scoping rules, and modern code doesn't use it.

const stops you reassigning the name, not changing what's inside an object: a const array can still have items pushed onto it.

Build strings with template literals, which use backticks and ${} to insert values:

const message = `${city} has ${bottles} bottles`

Comparing values

Always compare with === (strict equality) and !==. The older == converts types before comparing, so 0 == '' and '1' == 1 are both true, which hides bugs. Almost every team's linter rules out ==.

In an if, any value counts as true or false. The falsy values you'll meet are false, 0, '' (the empty string), null, undefined and NaN. Everything else is truthy, including '0', empty arrays and empty objects.

Question

Quick check

A form field gives you the string '5'. Which comparison with the number 5 is true?
Pick an answer.

Functions

A function is a named, reusable piece of logic. It takes parameters and returns a value.

function litresNeeded(people, days) {
  return people * days * 4
}

const total = litresNeeded(3, 7) // 84

You'll see the shorter arrow function syntax constantly, especially for small functions passed to other functions:

const litresNeeded = (people, days) => people * days * 4

The most important habit: a function that computes something should return it, not console.log it. A returned value can be tested, stored, shown in the page or passed to another function. A logged value just disappears into the console. Functions that only take inputs and return outputs, without changing anything else, are called pure functions, and they're the easiest code there is to test.

Arrays

An array is an ordered list. Items are numbered from 0, and .length says how many there are.

const prices = [1250, 899, 2400]
prices[0]        // 1250
prices.length    // 3
prices.push(300) // adds to the end

Modern JavaScript processes arrays with methods that take a function, rather than with hand-written counting loops:

  • map makes a new array by transforming each item: prices.map((p) => p * 2).
  • filter keeps the items that pass a test: prices.filter((p) => p > 1000).
  • find returns the first item that passes a test, or undefined.
  • reduce combines all items into one value, such as a sum.
  • forEach runs a function for each item, for side effects like logging.

A classic for...of loop is also perfectly good, and often clearer for beginners:

let sum = 0
for (const price of prices) {
  sum += price
}

Try it: write two small functions for a checkout.

Challenge

Checkout helpers

Prices are stored in cents. Write two functions:

  1. total(prices) returns the sum of an array of numbers. An empty array should give 0.
  2. formatPrice(cents) returns a string like "$12.50" (always two decimal places).

The last line logs the cart total using both. Press Run to try them.

Console
  1. Nothing logged yet.
  • total() adds up an array of numbers
  • total() of an empty array is 0
  • formatPrice() shows dollars with two decimal places
  • The console shows the cart total, $45.49

Objects

An object groups related values under named properties. Read them with a dot:

const item = { name: 'Water', qty: 12, unit: 'litres' }
item.name      // 'Water'
item.qty += 6  // now 18

Real data is almost always an array of objects: products, messages, users, supply lists. Combining array methods with objects is most of the everyday logic in a web app, such as "show the names of everything that's running low".

const names = items
  .filter((item) => item.qty < 3)
  .map((item) => item.name)

Chaining like this reads as a sentence: from the items, keep the low ones, then take their names. Neither filter nor map changes the original array; each returns a new one. Not changing data you were given (immutability) avoids a whole class of bugs where one part of an app quietly alters data another part relies on.

Handling missing values

Real data has gaps: a user with no phone number, an item with no unit, a search with no result. Reading a property of undefined is the most common error in JavaScript, so the language has two operators just for this:

const found = items.find((item) => item.name === 'Flour') // undefined
found?.qty          // undefined, instead of throwing an error
found?.qty ?? 0     // 0

Optional chaining (?.) stops and gives undefined if the value on its left is null or undefined. The nullish coalescing operator (??) supplies a fallback for null or undefined only, so a real 0 or '' is kept. The older || would replace those too, which is a frequent source of "the count shows 5 when it should show 0" bugs.

Question

Quick check

function double(n) { console.log(n * 2) } prints the right number. What does double(4) + 1 evaluate to?
Pick an answer.

Challenge

Work with a supply list

supplies is an array of objects. Write:

  1. lowStock(items, minimum): return an array of the names of items whose qty is below minimum, in their original order.
  2. findItem(items, name): return the item whose name matches, ignoring upper and lower case, or undefined if there isn't one.
  3. Log every item on its own line, like Water: 12 litres.
Console
  1. Nothing logged yet.
  • lowStock() returns the names of items below the minimum
  • lowStock() leaves the original array unchanged
  • findItem() matches names ignoring case
  • findItem() returns undefined when nothing matches
  • The console lists every item with its quantity and unit

Recap

  • Values have types; use === for comparisons and store money as whole cents to avoid floating-point surprises.
  • Use const by default and let when you need to reassign; build strings with template literals.
  • Functions should return their results; pure functions are the easiest to test and reuse.
  • Arrays of objects are the shape of most real data; filter, map, find and reduce transform them without changing the original.

Finished this lesson?

Mark it complete to track your progress on this device.