Vividly / Languages / JavaScript

JavaScript

JavaScript is the language of the web browser, used to make pages interactive and, through Node.js, to build servers and tools, and it is often the first language web developers learn.

Read the lesson →

Why this matters

You use JavaScript whenever a web page needs to respond to a person: validating a form, updating a shopping cart, animating a menu, or fetching data without reloading. Every modern browser runs it, so it is the one language you can count on being available on almost every device.

Beyond the browser, JavaScript powers servers with Node.js, mobile apps with React Native, desktop apps with Electron, and a huge ecosystem of packages. Learning it once opens several kinds of projects, which is why it is often the most useful first programming language.

It is also a forgiving language to start with. You can write a few lines, open a file in a browser, and see the result immediately. That short feedback loop makes experimenting cheap and helps you learn by doing.

The big picture

JavaScript programs are built from values and the functions that operate on them. Values have types: numbers, strings, booleans, objects, and a few special ones such as null and undefined. Unlike Python, JavaScript is loosely typed and will happily convert between types, which is convenient but can produce surprising results.

Nearly everything in JavaScript is an object, including functions. An object is a bundle of properties, each a name pointing to a value. Arrays are objects with numeric indexes and a length, and they are the container you will use most often.

The browser adds the Document Object Model, or DOM, which is a tree of objects representing the page. Your JavaScript waits for events, such as clicks, and responds by changing that tree. Understanding that event-driven model is the key to modern browser code.

Core ideas

Variables: let and const

You declare a variable with let when its value will change, and with const when it will not. Using const by default is a good habit because it catches accidental reassignment and tells readers the binding is stable. The old keyword var still works but has confusing function-scope behaviour, so modern code avoids it.

Assignment uses a single equals sign. Names are case sensitive, and by convention you write them in camelCase such as userName. Unlike Python, JavaScript has no indentation-based blocks; braces define where a block begins and ends, and semicolons end statements, though the language can often insert them for you.

Variables: let and constexample
let count = 0;
const name = 'Ada';
count = count + 1;
console.log(name, count);

Watch out. const prevents reassignment of the binding, not mutation of the object it holds. You can still change a property on a const object. Do not assume const freezes the value.

Types and coercion

JavaScript has primitive types: number, string, boolean, undefined, null, symbol, and bigint. Everything else is an object. You rarely declare types; the engine figures them out at runtime. Use typeof to inspect a value, but be aware that typeof null reports object, a long-standing quirk.

The language converts types automatically in many situations, called coercion. Adding a number and a string concatenates them, so the string five plus one gives fifty-one as text. Comparing with two equals signs also coerces, which is why you should almost always use strict equality that checks both value and type.

Types and coercionexample
let n = '5';
console.log(n + 1);
console.log(Number(n) + 1);
console.log(5 == '5', 5 === '5');

Watch out. Never rely on loose equality to compare values. It treats zero, false, and empty strings as equal in surprising ways. Reach for strict equality unless you specifically want coercion.

Arrays and objects

An array is an ordered list written with square brackets. You read items by index starting at zero, add them with push, and transform them with powerful methods such as map, filter, and reduce. These methods take functions as arguments and return new arrays, which keeps your data flow predictable.

An object groups named properties inside braces. You access them with dot notation or bracket notation. Objects are the backbone of JavaScript data, including data that arrives from an API as JSON. Arrays and objects can nest inside each other to represent almost any structure.

Arrays and objectsexample
const nums = [1, 2, 3];
const doubled = nums.map(n => n * 2);
const user = { name: 'Ada', age: 36 };
console.log(doubled, user.name);

Watch out. Methods like map and filter return a new array and leave the original alone. If you ignore the return value, nothing changes. Assign the result to a variable.

Conditionals

An if statement runs a block when its condition is truthy. JavaScript decides truthiness for you: values such as zero, empty strings, null, undefined, and NaN are falsey, while most others are truthy. Add else if branches for more cases and a final else for the fallback.

You can also use the ternary operator for short choices and switch when comparing one value against many options. Remember that switch uses strict equality, and each case needs a break or execution falls through to the next case.

Conditionalsexample
const temp = 30;
if (temp > 25) {
  console.log('hot');
} else if (temp > 15) {
  console.log('warm');
} else {
  console.log('cold');
}

Watch out. Forgetting break in a switch case causes fall-through, running several blocks. Add break at the end of each case unless you intentionally want that behaviour.

Loops

A for loop is the most common way to repeat work a known number of times. You write an initializer, a condition, and an update in the loop header. For walking through arrays, the for...of loop is cleaner because it gives you each value directly without managing an index.

A while loop repeats while a condition holds, useful when you cannot predict the count. Use break to exit and continue to skip an iteration. In modern JavaScript you will often use array methods such as forEach or map instead of writing a loop by hand, especially when transforming data.

Loopsexample
for (let i = 0; i < 3; i++) {
  console.log(i);
}
for (const fruit of ['apple', 'pear']) {
  console.log(fruit);
}

Watch out. Off-by-one errors are common: a loop with i < 3 runs three times with values zero, one, and two. If you need one through three, start at one or change the condition carefully.

Functions

A function packages reusable work. You can declare one with the function keyword, assign a function expression to a variable, or write a short arrow function. Each form has slightly different behaviour around hoisting and the this keyword, which you will explore in the deep dive.

You call a function with parentheses, passing arguments that become its parameters. A function returns a value with return; without one, it returns undefined. Because functions are values in JavaScript, you can store them in variables, pass them to other functions, and return them from functions.

Functionsexample
function greet(name) {
  return 'Hello, ' + name;
}
const shout = name => greet(name).toUpperCase();
console.log(shout('Ada'));

Watch out. Arrow functions without braces return a value implicitly, but adding braces means you must write return. Mixing the two is a frequent source of undefined results.

The DOM and events

The Document Object Model is a tree of objects representing everything on a web page. You select elements with document.querySelector, then change their text, styles, or attributes. This is how JavaScript turns a static page into something that responds to a person.

Events are signals such as clicks, key presses, or form submissions. You register a listener with addEventListener, giving it the event name and a function to run. That function, often called a callback, receives an event object describing what happened.

The DOM and eventsexample
const button = document.querySelector('#go');
button.addEventListener('click', event => {
  console.log('clicked', event.target);
});

Watch out. Running a script before the page has loaded means querySelector finds nothing and returns null. Put your script at the end of the body or wait for the DOMContentLoaded event.

Promises and async

Some work, like fetching data from a server, takes time. A promise is an object representing a result that will arrive later. You attach a then handler for success and a catch handler for failure, or you write async functions and use await to pause until the promise settles.

An async function always returns a promise. Inside it, await makes asynchronous code read like ordinary step-by-step code, which is much easier to follow than nested callbacks. Handling errors with try and catch around await is the modern standard.

Promises and asyncexample
async function load() {
  const response = await fetch('/api/users');
  const users = await response.json();
  return users.length;
}
load().then(console.log).catch(console.error);

Watch out. Forgetting await means you work with the promise object instead of the value it resolves to. If you see a pending promise in your output, look for a missing await.

Functions

Functions are the most important tool in JavaScript. You have already used them to package work and to react to events, but the language offers several forms, each with its own rules. Knowing which form to reach for will make your code shorter and less surprising.

The topics below move from how you write a function, through how it captures values and context, to how functions are passed around as data. That final idea, treating functions as values, is what makes callbacks, array methods, and frameworks work.

Declarations and expressions

A function declaration uses the function keyword followed by a name and a body. A function expression creates a function as part of an expression, often assigning it to a variable. Both produce callable values, but declarations are hoisted, meaning you can call them before the line that defines them.

Expressions are not hoisted in the same usable way, so you must define them before use. In practice, prefer the form that fits the job: declarations for named helpers, expressions when you want a function as a value or passed straight into another call.

Declarations and expressionsexample
function add(a, b) { return a + b; }
const sub = function (a, b) { return a - b; };
console.log(add(3, 1), sub(3, 1));

Arrow functions

Arrow functions are a compact syntax introduced in modern JavaScript. If the body is a single expression, you can omit braces and the expression is returned automatically. If you write braces, you must use return just like a regular function.

The deeper difference is how arrows handle this. An arrow does not have its own this; it captures the value from the surrounding scope. That makes them ideal for short callbacks inside methods, but poor choices for object methods that need to refer to the object itself.

Arrow functionsexample
const double = n => n * 2;
const sum = (a, b) => a + b;
const make = () => ({ ok: true });

Parameters and defaults

Parameters are listed inside parentheses. If a caller omits one, it becomes undefined. You can supply a default value with an equals sign, and the default is used only when the argument is missing or undefined. This makes options easy to add without breaking existing calls.

A rest parameter written with three dots collects any remaining arguments into an array. It must be the last parameter. Together, defaults and rest parameters let one function handle a wide range of calls while keeping its signature readable.

Parameters and defaultsexample
function greet(name = 'friend', ...rest) {
  return 'Hi ' + name + rest.join('');
}
console.log(greet('Ada', '!', '!'));

Return values

The return statement ends a function and hands a value back to the caller. You can return any value, including objects, arrays, and other functions. A function that falls off the end without returning gives back undefined, which is a common cause of mysterious results.

Returning early is a clean way to handle invalid input or simple cases. Instead of wrapping the whole function in an if block, you check the edge case, return, and let the remaining code deal only with the normal situation.

Return valuesexample
function size(list) {
  if (!list) return 0;
  return list.length;
}
console.log(size([1, 2]));

Closures

A closure is a function that keeps access to variables from the scope where it was created, even after that outer function has finished. In JavaScript this happens naturally because functions carry a reference to their defining environment.

Closures let you keep private state without a class. A function can create a local variable, then return an inner function that reads or changes it. Each call gets its own copy of that state, which is exactly what you want for counters, memoization, and factories.

Closuresexample
function counter() {
  let n = 0;
  return () => ++n;
}
const next = counter();
console.log(next(), next());

The this keyword

The this keyword refers to the object a function was called on, but its value is decided at call time, not when the function is written. Calling obj.method() sets this to obj, while calling the same function on its own usually leaves this undefined in strict mode.

Arrow functions are the exception: they take this from their surrounding scope instead. When a callback needs the object's this, use a regular function or bind it. When you want to keep an outer this inside a nested callback, an arrow is usually the right choice.

The this keywordexample
const person = {
  name: 'Ada',
  say() { return this.name; }
};
console.log(person.say());

Callbacks and higher-order functions

A higher-order function is a function that accepts another function as an argument or returns one. Array methods such as map, filter, and reduce are higher-order functions: you give them a callback that describes what to do with each item.

This style keeps a clean separation between the mechanism, which walks the collection, and your decision, which lives in the callback. It also composes well, because you can chain methods and pass named functions around instead of duplicating loops.

Callbacks and higher-order functionsexample
const nums = [1, 2, 3, 4];
const even = nums.filter(n => n % 2 === 0);
console.log(even);

Hoisting and scope

Hoisting is the engine's habit of moving declarations to the top of their scope before code runs. Function declarations and var declarations are hoisted, while let and const are also hoisted but remain in a temporary dead zone until their initializer is reached.

JavaScript has function scope and block scope. A var variable leaks out of an if block to the whole function, which is why loops with var have classic bugs. Using let and const gives each block its own binding, and that is a major reason modern code avoids var.

Hoisting and scopeexample
console.log(f());
function f() { return 'ok'; }
for (let i = 0; i < 2; i++) { const x = i; }

Function reference

These are the functions you will reach for most often. Each one is shown with its syntax, its inputs and outputs, a working example, and the mistakes to avoid.

function declaration

User-defined form

A function declaration defines a named function you can call anywhere in its scope. You use it for reusable logic that benefits from a clear name, because declarations are hoisted and ready before their line.

Syntaxfunction name(parameters) { body }
Parametersname — The identifier used to call the function
parameters — Comma-separated input values
ReturnsWhatever the function returns with the return statement, otherwise undefined.
function declarationexample
function greet(name) {
  return "Hello, " + name + "!";
}

console.log(greet("Ada"));

What you can do with it. Package reusable calculations under a name Define event handlers and utilities Break a large script into small callable pieces

Choose it when. Choose a function declaration for named, reusable logic rather than a short inline callback.

MistakeFix
Forgetting the return keywordUse return to send a value back; otherwise you get undefined
Assuming it is unavailable before its lineDeclarations are hoisted, so you can call them earlier in the same scope

function expression

User-defined form

A function expression creates a function as part of an expression, often assigned to a variable. You use it when a function is a value you can pass around, store in an object, or choose conditionally.

Syntaxconst name = function(parameters) { body };
Parametersparameters — Comma-separated input values
name — Optional internal name for recursion or errors
ReturnsWhatever the function explicitly returns, otherwise undefined.
function expressionexample
const square = function(n) {
  return n * n;
};

console.log(square(4));

What you can do with it. Store a function in a variable or object property Choose between two implementations at runtime Pass an anonymous function as an argument

Choose it when. Choose a function expression when you want a function value rather than a fixed named declaration.

MistakeFix
Calling it before the assignment lineFunction expressions are not hoisted like declarations; define them first
Confusing it with a declaration for hoistingRemember only declarations are hoisted with their body

arrow function

User-defined form

An arrow function is a compact way to write a function, and it does not bind its own this. You use it for short callbacks and when you want this to come from the surrounding scope.

Syntax(parameters) => expression or (parameters) => { body }
Parametersparameters — Inputs; parentheses can be omitted for one parameter
body — Expression returned implicitly, or a block with return
ReturnsThe expression value, or whatever a block body returns.
arrow functionexample
const add = (a, b) => a + b;
console.log(add(2, 3));

const nums = [1, 2, 3];
console.log(nums.map(n => n * 2));

What you can do with it. Write short callbacks for map, filter, and reduce Preserve this inside methods and timers Create concise one-line helpers

Choose it when. Choose an arrow function for short callbacks and lexical this rather than a verbose function expression.

MistakeFix
Using one as a constructor or method needing thisUse a regular function when you need its own this binding
Expecting arguments to work inside itArrows have no arguments object; use rest parameters instead

callback

User-defined form

A callback is a function you pass into another function to be run later. You use it to respond to events or customize how an operation behaves without changing the operation itself.

Syntaxfunction doWork(value, callback) { ... callback(result); }
Parameterscallback — The function invoked when work completes
value — Input the outer function processes
ReturnsCallbacks usually return nothing useful; their result is delivered by calling them.
callbackexample
function process(value, callback) {
  const result = value * 2;
  callback(result);
}

process(5, function(result) {
  console.log(result);
});

What you can do with it. Handle results of asynchronous operations Customize sorting or iteration behavior Register event listeners

Choose it when. Choose a callback when you need to run code after an operation rather than blocking to wait for it.

MistakeFix
Forgetting to actually call the callbackInvoke callback(...) inside the outer function when work is done
Calling it multiple times by accidentMake sure the code path calls the callback exactly once

closure

User-defined form

A closure is a function that remembers variables from the scope where it was created. You use it to keep private state alive between calls without relying on global variables.

Syntaxfunction outer() { let x = 0; return function() { return ++x; }; }
ReturnsAn inner function that keeps access to the outer variables.
closureexample
function makeCounter() {
  let count = 0;
  return function() {
    return ++count;
  };
}

const next = makeCounter();
console.log(next(), next());

What you can do with it. Create counters with hidden state Build function factories with presets Protect data from outside modification

Choose it when. Choose a closure when a function must remember state between calls rather than storing it globally.

MistakeFix
Using var in a loop and expecting per-iteration valuesUse let so each closure captures its own binding
Assuming state resets on every inner callThe captured value persists; call the outer function again for fresh state

async function

User-defined form

An async function works with promises and lets you write await inside it. You use it to handle asynchronous work in a readable, top-to-bottom style instead of nesting callbacks.

Syntaxasync function name(parameters) { const value = await promise; }
Parametersparameters — Input values passed to the function
promise — An awaited value from another async call
ReturnsA promise that resolves to the function's returned value.
async functionexample
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

async function loadUser(id) {
  await wait(100);
  return { id: id, name: "Ada" };
}

loadUser(1).then(user => console.log(user.name));

What you can do with it. Load data and process the result in order Sequence multiple dependent async steps Wrap promise chains in readable code

Choose it when. Choose an async function when you have dependent asynchronous steps rather than nested .then callbacks.

MistakeFix
Forgetting await on a promise-returning callAdd await so you work with the resolved value, not the promise
Using await outside an async functionMark the containing function async, or use a top-level await environment

map

Array method

map creates a new array by running a function on every element. You use it when you want to transform each item into something else without mutating the original list.

Syntaxarray.map((element, index) => expression)
Parameterselement — The current item
index — The item's position; optional
ReturnsA new array of the same length containing the transformed values.
mapexample
const nums = [1, 2, 3];
const doubled = nums.map(n => n * 2);
console.log(doubled);

const users = [{name: "Ada"}];
console.log(users.map(u => u.name));

What you can do with it. Extract a property from a list of objects Convert values from one form to another Render list items into elements

Choose it when. Choose map when you need one output per input rather than filtering or just looping.

MistakeFix
Forgetting to return a value from the callbackReturn the transformed value, or use a concise arrow expression
Expecting the original array to changemap returns a new array and leaves the original untouched

filter

Array method

filter builds a new array containing only the items that pass a test. You use it when you want to keep a subset of a list based on a condition.

Syntaxarray.filter((element) => condition)
Parameterselement — The current item
index — The item's position; optional
ReturnsA new array of items for which the callback returned true.
filterexample
const nums = [1, 2, 3, 4];
const evens = nums.filter(n => n % 2 === 0);
console.log(evens);

const words = ["go", "hello", "hi"];
console.log(words.filter(w => w.length > 2));

What you can do with it. Keep items that match a condition Remove invalid or unwanted entries Build search results from a list

Choose it when. Choose filter when you want fewer items rather than transforming every item.

MistakeFix
Returning the element instead of a booleanReturn true or false from the callback
Expecting the original array to be modifiedfilter returns a new array; reassign it to replace the original

reduce

Array method

reduce combines all items in an array into a single value by repeatedly applying a function. You use it to compute totals, counts, or grouped results from a list.

Syntaxarray.reduce((accumulator, element) => expression, initialValue)
Parametersaccumulator — The running value carried between steps
element — The current item
initialValue — Starting value for the accumulator
ReturnsThe final accumulator value.
reduceexample
const nums = [1, 2, 3, 4];
const total = nums.reduce((sum, n) => sum + n, 0);
console.log(total);

const counts = ["a", "b", "a"].reduce((acc, x) => {
  acc[x] = (acc[x] || 0) + 1;
  return acc;
}, {});

What you can do with it. Sum or multiply a list of numbers Count occurrences of values Flatten or group data into one object

Choose it when. Choose reduce when you need one combined result rather than a new array of the same length.

MistakeFix
Forgetting the initial valueProvide one to avoid errors on empty arrays and keep a stable type
Forgetting to return the accumulatorReturn the updated accumulator on every step

forEach

Array method

forEach runs a function once for each item in an array. You use it when you want a side effect per item, like logging or updating the page, and do not need a new array back.

Syntaxarray.forEach((element, index) => { ... })
Parameterselement — The current item
index — The item's position; optional
Returnsundefined; forEach does not build a result.
forEachexample
const names = ["Ada", "Bob"];
names.forEach(name => console.log(name));

const boxes = [1, 2];
boxes.forEach((n, i) => console.log(i, n));

What you can do with it. Log or display each item Trigger side effects for each element Replace a simple for loop over an array

Choose it when. Choose forEach for side effects on each item rather than producing a transformed array.

MistakeFix
Expecting forEach to return a new arrayUse map or filter when you need a result
Trying to break out of the loop earlyforEach cannot break; use a for loop or some()/find()

find

Array method

find returns the first item that passes a test. You use it when you want to locate one matching element instead of collecting every match into a new array.

Syntaxarray.find((element) => condition)
Parameterselement — The current item
index — The item's position; optional
ReturnsThe first matching element, or undefined if none matches.
findexample
const users = [{id: 1, name: "Ada"}, {id: 2, name: "Bob"}];
const user = users.find(u => u.id === 2);
console.log(user.name);

console.log([1, 3, 5].find(n => n > 3));

What you can do with it. Look up a record by id Get the first item meeting a condition Check whether a matching item exists

Choose it when. Choose find when you need the first matching item rather than every match or just a boolean.

MistakeFix
Assuming it returns all matchesfind stops at the first match; use filter for all matches
Forgetting it can return undefinedHandle the undefined case before using the result

JSON.parse

Parse/serialize function

JSON.parse turns a JSON string into a JavaScript value. You use it whenever you receive JSON text from storage or a response and need real objects and arrays to work with.

SyntaxJSON.parse(text, reviver)
Parameterstext — The JSON string to parse
reviver — Optional function that transforms each parsed value
ReturnsThe JavaScript value represented by the JSON text.
JSON.parseexample
const text = '{"name":"Ada","age":36}';
const user = JSON.parse(text);
console.log(user.name);

const nums = JSON.parse("[1,2,3]");
console.log(nums[0]);

What you can do with it. Convert stored JSON strings back into objects Read structured data from a response Rebuild configuration from text

Choose it when. Choose JSON.parse when you have JSON text as a string rather than an already-parsed object.

MistakeFix
Passing an object instead of a stringJSON.parse expects text; stringify an object first if needed
Not handling malformed inputWrap parsing in try/catch because bad JSON throws an error

parseInt

Built-in function

parseInt converts a string into an integer, stopping at the first non-digit. You use it when you need a whole number from text, such as a value typed into a form field.

SyntaxparseInt(string, radix)
Parametersstring — The text to convert
radix — The numeric base, usually 10
ReturnsAn integer parsed from the string, or NaN if it cannot start a number.
parseIntexample
console.log(parseInt("42"));
console.log(parseInt("42px"));
console.log(parseInt("ff", 16));
console.log(parseInt("hello"));

What you can do with it. Read numeric values from form fields Convert hex or binary strings with radix Extract a leading integer from mixed text

Choose it when. Choose parseInt when you want a leading integer from text rather than a strict numeric conversion.

MistakeFix
Forgetting the radix argumentPass 10 to avoid legacy octal interpretation of leading zeros
Assuming partial text is an errorparseInt stops at the first non-digit; use Number() for strict conversion

Array.isArray

Built-in function

Array.isArray checks whether a value is an array. You use it to avoid treating other objects as lists, which is especially important after parsing data you did not create yourself.

SyntaxArray.isArray(value)
Parametersvalue — The value to test
Returnstrue if the value is an array, otherwise false.
Array.isArrayexample
console.log(Array.isArray([1, 2]));
console.log(Array.isArray({0: "a"}));

const data = JSON.parse('[1,2,3]');
if (Array.isArray(data)) {
  console.log("got a list");
}

What you can do with it. Validate parsed JSON before iterating Distinguish arrays from array-like objects Guard functions that expect list input

Choose it when. Choose Array.isArray when you need a reliable array check rather than a typeof test.

MistakeFix
Using typeof to detect arraystypeof returns object for arrays; use Array.isArray instead
Forgetting null is not an arrayCheck the value first; Array.isArray(null) is simply false

Common mistakes here

MistakeFix
Using an arrow function when you need this to refer to the calling object.Use a regular method function, because arrows capture this from their defining scope.
Returning an object literal from an arrow without parentheses.Wrap it like this: () => ({ key: value }), since braces are read as a function body.
Forgetting return in a braced arrow function.Write return explicitly, or use the expression form without braces.
Assuming var and let behave the same way.Prefer const and let, since var is function-scoped and hoisted in a confusing way.
Thinking hoisting moves let initialization to the top.Declarations are hoisted but stay in the temporal dead zone until initialized.

The example, line by line

This program takes a small list of products, keeps the expensive ones, and computes a subtotal using function values and array methods.

CodeWhat it does
1const items = [Start an array of product objects, each with a name, a price, and a quantity.
2 { name: 'Pen', price: 1.5, qty: 3 },The first product is a cheap pen with three units.
3 { name: 'Book', price: 12, qty: 1 },The second product is a single book.
4 { name: 'Eraser', price: 0.5, qty: 2 }The third product is a cheap eraser with two units.
5];Close the array literal and store it in a constant binding.
6function lineTotal(item) {Define a named function that works out one line's cost.
7 return item.price * item.qty;Multiply price by quantity and return the result to the caller.
8}Close the function body.
9const expensive = items.filter(item => item.price > 1);Filter keeps only products whose price exceeds one, using a short arrow callback.
10const total = expensiveBegin a chain that will turn the remaining items into numbers.
11 .map(lineTotal)Pass lineTotal as a function value so map applies it to every item.
12 .reduce((sum, n) => sum + n, 0);Reduce adds the numbers together, starting from zero.
13console.log('Subtotal:', total.toFixed(2));Print the result formatted to two decimal places for money.
Full examplecomplete
const items = [
  { name: 'Pen', price: 1.5, qty: 3 },
  { name: 'Book', price: 12, qty: 1 },
  { name: 'Eraser', price: 0.5, qty: 2 }
];
function lineTotal(item) {
  return item.price * item.qty;
}
const expensive = items.filter(item => item.price > 1);
const total = expensive
  .map(lineTotal)
  .reduce((sum, n) => sum + n, 0);
console.log('Subtotal:', total.toFixed(2));

Worked variations

A todo list renderer

In a browser, a function often turns data into elements. Here a small function builds a list item from a task string and appends it to the page, which you might call from a loop over an array.

Because the renderer is a function, you can test it with different inputs and reuse it whenever the task list changes.

A todo list renderervariation
function addItem(text) {
  const li = document.createElement('li');
  li.textContent = text;
  document.querySelector('#todo').append(li);
}
addItem('Write tests');

Chaining array methods

Array methods shine when you chain them. Each step receives the output of the previous one, so you can filter, transform, and sort without writing temporary loops.

Read the chain from top to bottom as a series of questions about your data. That habit makes even long chains easy to follow.

Chaining array methodsvariation
const scores = [40, 72, 91, 58, 85];
const top = scores
  .filter(n => n >= 60)
  .map(n => n + 5)
  .sort((a, b) => b - a);
console.log(top);

Common mistakes

MistakeFix
Comparing values with two equals signs instead of three.Use strict equality so both value and type must match.
Treating a const object as if it could not change.Remember that const fixes the binding only. Use Object.freeze if you truly need immutability.
Starting an index loop at zero but using a less than or equal condition.Check the number of iterations out loud, then choose the right start and condition.
Forgetting to return a value from a callback passed to map.Use the expression form or write an explicit return so the new array is filled.
Using a plain function as a timer callback that needs the outer this.Use an arrow function so this is captured from the surrounding scope.

Practice

  1. Write a function that takes an array of names and returns a greeting string for each one.
  2. Use filter and map to get the squared values of the even numbers from one to twenty.
  3. Create a counter factory function that returns isolated counters with an increment method.
  4. Build a small calculator object whose methods use this, then call them with and without the object to see the difference.
Atmospheric photograph for this chapter Curved glass and steel lattice roof Stepped white modern building corner
Structure comes first. Read the idea, then build something small of your own.

Where next