JavaScript AcademyProfessional Engineering

JavaScript code examples

206 runnable examples, each generated from its source file, with expected output, common mistakes and a modification challenge. Filter by concept, level, feature or environment.

ex-001-01 · Lesson 1

Your first output

console.log prints whatever you put between its parentheses. Each call prints one line, in the order the lines appear.

ex-001-02 · Lesson 1

JavaScript calculates

Numbers and arithmetic operators outside quotes are calculated. Multiplication happens before addition, as in ordinary maths.

ex-001-03 · Lesson 1

One language, many hosts

These lines use only the JavaScript language itself, so they behave the same in a browser, a worker and Node.js.

ex-001-04 · Lesson 1

JavaScript changes a page

In a browser page, JavaScript can find an element and change its text. The preview below runs this code in a sandboxed page.

ex-002-01 · Lesson 2

Order matters

Statements run from top to bottom, so the output appears in the same order as the lines.

ex-002-02 · Lesson 2

Strings and numbers with +

With two numbers, + adds. If either side is a string, + joins text instead.

ex-002-03 · Lesson 2

Remember a value

let creates a named value that can change. The right-hand side is worked out first, then stored.

ex-002-04 · Lesson 2

A tiny greeting program

Constants hold values that do not change. Strings and numbers combine with + to build sentences.

ex-003-01 · Lesson 3

Expressions produce values

Each console.log receives the value of an expression. Precedence and parentheses change the grouping.

ex-003-02 · Lesson 3

Statements do work

Declarations and assignments are statements. The final value of total depends on each statement running in order.

ex-003-03 · Lesson 3

Comments are ignored

Comments never run. A commented-out console.log prints nothing.

ex-003-04 · Lesson 3

A value nobody looks at

An expression statement is evaluated, but if its value is not printed or stored, nothing visible happens.

ex-004-01 · Lesson 4

Several values in one log

Commas separate values; console.log prints them with a space between.

ex-004-02 · Lesson 4

Log levels

warn and error stand out from ordinary log lines. The academy console colours them, as browser tools do.

ex-004-03 · Lesson 4

Tables for collections

console.table lays out a list of records as rows and columns. console.log shows the same data on one line. You will learn about lists (arrays) and records (objects) in Level 2.

ex-004-04 · Lesson 4

Trace a calculation with groups

console.group indents the lines that follow until console.groupEnd, which keeps a step-by-step trace tidy.

ex-005-01 · Lesson 5

A ReferenceError

The first log runs. The second uses a misspelled name, so it stops with a ReferenceError and the last line never runs.

ex-005-02 · Lesson 5

A TypeError

price holds a number. Adding () tries to call it as a function, which numbers cannot do.

ex-005-03 · Lesson 5

A SyntaxError stops everything

Line 2 is missing its closing parenthesis. JavaScript cannot read the program, so not even line 1 runs.

ex-005-04 · Lesson 5

Investigate with logs

No error appears, yet the result is wrong. Logging each step reveals that only the discount was divided by 100.

ex-006-01 · Lesson 6

let changes, const stays

The price is fixed, so it is a const. The quantity changes, so it is a let and is reassigned without the keyword.

ex-006-02 · Lesson 6

A running total

A let variable can grow step by step. Each assignment reads the old value and stores a new one.

ex-006-03 · Lesson 6

Assigning to a const

Assigning to a const stops the program with a TypeError. Everything before that line has already run.

ex-006-04 · Lesson 6

Names that explain themselves

Both programs compute the same thing. The second one can be read without any comments.

ex-007-01 · Lesson 7

Three ways to build a message

+ needs explicit spaces; a template literal reads like the final text.

ex-007-02 · Lesson 7

Useful string methods

Each method returns a new string or a value about the string. The original stays the same.

ex-007-03 · Lesson 7

Quotes, new lines and multi-line text

A backslash lets you put special characters inside a string. Template literals can also span lines.

ex-007-04 · Lesson 7

When + joins instead of adds

If either side of + is a string, JavaScript joins text. This is the source of many "123" bugs.

ex-008-01 · Lesson 8

Arithmetic operators

The six operators cover most calculations. % gives the remainder, ** the power.

ex-008-02 · Lesson 8

Floating-point surprises

Binary decimals cause tiny errors. Round for display, or work in whole cents.

ex-008-03 · Lesson 8

The Math toolbox

Math methods round, compare and pick numbers.

ex-008-04 · Lesson 8

NaN and Infinity

Some operations have no normal numeric result. Check with Number.isNaN before showing a value.

ex-009-01 · Lesson 9

Booleans from comparisons

Comparisons answer yes/no questions with true or false.

ex-009-02 · Lesson 9

undefined versus null

undefined appears when nothing was assigned; null is assigned on purpose.

ex-009-03 · Lesson 9

Truthy and falsy

Boolean(x) shows how a value behaves in a condition. Only six values are falsy.

ex-009-04 · Lesson 9

When 0 is a real value

A quantity of 0 is valid data, but a truthiness check treats it as missing. ?? only replaces null and undefined.

ex-010-01 · Lesson 10

typeof every kind of value

typeof returns a string naming the type. Note the two quirks: null and arrays are "object".

ex-010-02 · Lesson 10

Explicit conversion

Number, String and Boolean convert on purpose.

ex-010-03 · Lesson 10

parseInt and parseFloat

The parse functions read a number from the start of text and stop at the first character that does not fit.

ex-010-04 · Lesson 10

Implicit coercion

Arithmetic operators other than + convert text to numbers; + joins if either side is text.

ex-011-01 · Lesson 11

The comparison operators

Each comparison produces true or false.

ex-011-02 · Lesson 11

Strict versus loose equality

== converts types first; === never does.

ex-011-03 · Lesson 11

Comparing strings

Strings compare by character codes. Capitals sort before lowercase letters.

ex-011-04 · Lesson 11

Arrays compare by reference

Two arrays with the same contents are still two different arrays.

ex-012-01 · Lesson 12

A truth table

Every combination of two booleans with && and ||.

ex-012-02 · Lesson 12

Combining real rules

Parentheses make mixed && and || rules match the sentence.

ex-012-03 · Lesson 12

Short-circuit evaluation

The right side runs only when needed. Here the log inside the function shows when it is called.

ex-012-04 · Lesson 12

&& and || return a value

|| returns the first truthy operand; && returns the first falsy one (or the last).

ex-013-01 · Lesson 13

if and else

One of the two blocks always runs.

ex-013-02 · Lesson 13

An else if chain

Only the first matching branch runs, so the thresholds go from highest to lowest.

ex-013-03 · Lesson 13

When the order is wrong

The first condition is too general, so the later ones can never run.

ex-013-04 · Lesson 13

Check the invalid cases first

Handling bad input first keeps the main calculation simple.

ex-014-01 · Lesson 14

switch with break

Exactly one case runs because each ends with break.

ex-014-02 · Lesson 14

Missing break: fall-through

Without break, execution continues into the next cases.

ex-014-03 · Lesson 14

Grouping cases on purpose

Several case labels can share one block.

ex-014-04 · Lesson 14

The conditional operator

A ternary chooses between two values inside an expression.

ex-015-01 · Lesson 15

Parking fee rules

Named constants keep the rules readable and easy to change.

ex-015-02 · Lesson 15

Testing the boundaries

Checking just below, at and above the limit catches off-by-one mistakes.

ex-015-03 · Lesson 15

Quiz result with reasons

Each outcome prints a specific reason.

ex-015-04 · Lesson 15

Specific feedback

Checking rules separately lets the program say exactly what is missing.

ex-016-01 · Lesson 16

Counting up

The counter starts at 1 and increases until the condition is false.

ex-016-02 · Lesson 16

Counting down and stepping

The update can subtract, or add more than one.

ex-016-03 · Lesson 16

Looping over an array by index

Indexes run from 0 to length - 1.

ex-016-04 · Lesson 16

for...of for each value

When you need values rather than positions, for...of is shorter.

ex-017-01 · Lesson 17

Until a goal is reached

The number of months is the result, not the input.

ex-017-02 · Lesson 17

Halving until small

Each pass changes the value the condition checks.

ex-017-03 · Lesson 17

do...while runs at least once

Even when the condition is false at the start, the body runs one time.

ex-017-04 · Lesson 17

Stopping at a sentinel

The loop reads values until it finds the stop marker.

ex-018-01 · Lesson 18

break ends a search

Once the item is found there is no need to look further.

ex-018-02 · Lesson 18

continue skips items

Cancelled orders are skipped without nesting the rest of the body.

ex-018-03 · Lesson 18

continue in a counting loop

The update i++ still runs after continue.

ex-018-04 · Lesson 18

A flag instead of break

A condition in the loop header can replace break.

ex-019-01 · Lesson 19

Labelling seats

The outer loop picks the row; the inner loop picks the seat number.

ex-019-02 · Lesson 19

A star triangle

The inner loop's length depends on the outer counter.

ex-019-03 · Lesson 19

Counting inner iterations

The inner body runs outer × inner times.

ex-019-04 · Lesson 19

Reading a grid

grid[row][col] reaches each cell of an array of arrays.

ex-020-01 · Lesson 20

Total and average

An accumulator gives the total; dividing by the count gives the average.

ex-020-02 · Lesson 20

Counting matches

A counter only increases when the condition is true.

ex-020-03 · Lesson 20

Minimum and maximum together

Start from the first value so negative data works.

ex-020-04 · Lesson 20

A number problem

A while loop takes digits off a number one at a time.

ex-021-01 · Lesson 21

Declare once, call many times

The body runs each time the function is called.

ex-021-02 · Lesson 21

A function expression

A function can be stored in a const like any other value.

ex-021-03 · Lesson 21

Declarations are hoisted

A declaration can be called before the line that defines it.

ex-021-04 · Lesson 21

Functions are values

Printing a function shows the function, not its result.

ex-022-01 · Lesson 22

One parameter, many calls

Each call fills name with a different argument.

ex-022-02 · Lesson 22

Order matters

Arguments fill parameters by position.

ex-022-03 · Lesson 22

Default and missing values

A default replaces undefined, and only undefined.

ex-022-04 · Lesson 22

Any number of arguments

...prices collects all arguments into an array.

ex-023-01 · Lesson 23

Use the returned value

The call becomes its return value.

ex-023-02 · Lesson 23

Printing is not returning

A function that only logs gives back undefined.

ex-023-03 · Lesson 23

Early return

return stops the function, so later lines do not run.

ex-023-04 · Lesson 23

Returning several values

An object groups related results into one return value.

ex-024-01 · Lesson 24

Three ways to write one function

Declaration, expression and arrow give the same result.

ex-024-02 · Lesson 24

Block bodies need return

Braces turn off the automatic return.

ex-024-03 · Lesson 24

Arrows as callbacks

Short arrows are passed straight into array methods.

ex-024-04 · Lesson 24

Returning an object

Wrap an object literal in parentheses after =>.

ex-025-01 · Lesson 25

A small pipeline

Each helper does one job; the main function connects them.

ex-025-02 · Lesson 25

Validation returns a result

A validator returns an object instead of printing.

ex-025-03 · Lesson 25

Testing each piece

A tiny check function tests helpers one by one.

ex-025-04 · Lesson 25

Configuration as a parameter

Passing settings in makes functions reusable for other shops.

ex-026-01 · Lesson 26

Create and read an array

Indexes start at 0; length counts the elements.

ex-026-02 · Lesson 26

The last element

length - 1 and at(-1) both reach the end.

ex-026-03 · Lesson 26

Changing an element

Assigning to an index replaces that element, even in a const array.

ex-026-04 · Lesson 26

Calculating with elements

Elements are ordinary values, so you can calculate with them.

ex-027-01 · Lesson 27

Working at the end

push adds, pop removes and returns the removed element.

ex-027-02 · Lesson 27

Working at the start

unshift adds to the front; shift serves the front of a queue.

ex-027-03 · Lesson 27

Removing from the middle

splice changes the array and returns what it removed.

ex-027-04 · Lesson 27

slice and concat do not mutate

The original stays the same; a new array is returned.

ex-028-01 · Lesson 28

Searching by value

includes answers yes/no; indexOf gives a position.

ex-028-02 · Lesson 28

Searching by a rule

find returns the element; findIndex returns its position.

ex-028-03 · Lesson 28

Sorting numbers correctly

Default sort compares text; a - b compares numbers.

ex-028-04 · Lesson 28

Sorting objects by a property

The compare function reads the property to compare.

ex-029-01 · Lesson 29

Three loops, one result

Classic for, for...of and forEach can produce the same output.

ex-029-02 · Lesson 29

Index and value together

entries() with destructuring gives both.

ex-029-03 · Lesson 29

Looping over objects

Each element is an object; read its properties.

ex-029-04 · Lesson 29

Strings are iterable

for...of visits each character.

ex-030-01 · Lesson 30

Add and list

A counter makes ids unique; printList only reads.

ex-030-02 · Lesson 30

Update by id

find returns the object itself, so changing it updates the collection.

ex-030-03 · Lesson 30

Remove by id

findIndex locates the item; splice removes it.

ex-030-04 · Lesson 30

Summarise the collection

A summary function reads the state and returns numbers.

ex-031-01 · Lesson 31

Doing something for each element

The callback runs once per element.

ex-031-02 · Lesson 31

Passing a named function

Pass the function itself, without brackets.

ex-031-03 · Lesson 31

Updating an outer variable

A side effect: the callback adds to a total declared outside.

ex-031-04 · Lesson 31

Element, index and array

The third argument is the array itself.

ex-032-01 · Lesson 32

Transform numbers

One output for every input; the original stays the same.

ex-032-02 · Lesson 32

Objects to display strings

map turns data into lines to show.

ex-032-03 · Lesson 32

A block body needs return

Without return, every element becomes undefined.

ex-032-04 · Lesson 32

New objects, original untouched

Spread copies each object and adds a property.

ex-033-01 · Lesson 33

Keep what passes

filter returns a new, shorter (or equal) array.

ex-033-02 · Lesson 33

Filtering objects with two conditions

Combine conditions inside the predicate.

ex-033-03 · Lesson 33

Named predicates

Small named tests make filters readable.

ex-033-04 · Lesson 33

some and every

Yes/no questions about the whole list.

ex-034-01 · Lesson 34

Summing with reduce

The accumulator starts at 0 and grows.

ex-034-02 · Lesson 34

Finding the maximum

The accumulator keeps the best value seen so far.

ex-034-03 · Lesson 34

Counting per category

The accumulator is an object of counts.

ex-034-04 · Lesson 34

Totals per group

Grouping and summing in one pass.

ex-035-01 · Lesson 35

Filter, then map

Keep the paid orders, then turn them into labels.

ex-035-02 · Lesson 35

Top three

Sort, slice, then map.

ex-035-03 · Lesson 35

Ending with reduce

A pipeline can end with one summary value.

ex-035-04 · Lesson 35

Named steps

Small named functions make the pipeline read like requirements.

ex-036-01 · Lesson 36

Create and read

Dot notation reads a property; console.log shows the whole object.

ex-036-02 · Lesson 36

Update, add and delete

Objects change in place, even with const.

ex-036-03 · Lesson 36

Shorthand properties

When a variable has the same name as the key, write it once.

ex-036-04 · Lesson 36

Missing properties

A missing property is undefined; going deeper throws.

ex-037-01 · Lesson 37

Reading a key from a variable

Brackets evaluate the expression inside them.

ex-037-02 · Lesson 37

Computed keys

The key name comes from a variable.

ex-037-03 · Lesson 37

Looping over an object

Object.entries gives pairs for a for...of loop.

ex-037-04 · Lesson 37

Methods and this

A method reads the object's own data through this.

ex-038-01 · Lesson 38

Reading nested paths

Each . or [ ] moves one level deeper.

ex-038-02 · Lesson 38

Updating nested values

Assign at the end of a path.

ex-038-03 · Lesson 38

Looping over nested arrays

Outer loop over orders, inner loop over items.

ex-038-04 · Lesson 38

Nested data as JSON

JSON.stringify shows structure; JSON.parse reads it back.

ex-039-01 · Lesson 39

Primitives are copied

Changing y does not change x.

ex-039-02 · Lesson 39

Objects are shared

Two names, one object.

ex-039-03 · Lesson 39

Shallow copies share nested objects

Spread copies the outer level only.

ex-039-04 · Lesson 39

Deep copies and equality

structuredClone copies everything; === compares references.

ex-040-01 · Lesson 40

Entities and links

Loans link a member and a book by id.

ex-040-02 · Lesson 40

A factory with defaults and validation

Every created object has the same shape.

ex-040-03 · Lesson 40

Derive, do not duplicate

Line totals and the order total are calculated, never stored.

ex-040-04 · Lesson 40

One status instead of many booleans

A single status cannot contradict itself.

ex-041-01 · Lesson 41

Unpack an object

Each name in the braces becomes a variable holding that property.

ex-041-02 · Lesson 41

Unpack an array

Array destructuring works by position, and an empty slot skips one.

ex-041-03 · Lesson 41

Rename and default

A colon renames; = gives a fallback for undefined values.

ex-041-04 · Lesson 41

Destructured parameters

Unpacking in the parameter list shows exactly which properties a function needs.

ex-041-05 · Lesson 41

Swap two variables

Destructuring an array literal swaps values without a temporary variable.

ex-042-01 · Lesson 42

Combine arrays

Spread places each item of each array into the new array.

ex-042-02 · Lesson 42

Copy and update an object

Later properties override earlier ones.

ex-042-03 · Lesson 42

Rest parameters

Rest collects any number of arguments into a real array.

ex-042-04 · Lesson 42

Omit fields with object rest

Destructure the fields to drop and keep the rest.

ex-042-05 · Lesson 42

Spread is shallow

Nested objects are shared between the original and the copy.

ex-043-01 · Lesson 43

Read nested data safely

?. returns undefined instead of throwing.

ex-043-02 · Lesson 43

Add a fallback

?? supplies a value when the chain gives undefined.

ex-043-03 · Lesson 43

Optional method call

?.() calls a function only if it exists.

ex-043-04 · Lesson 43

Optional indexing

?.[ ] reads an index only when the array exists.

ex-044-01 · Lesson 44

|| versus ??

Only ?? keeps valid falsy values.

ex-044-02 · Lesson 44

Default parameters

Defaults apply when the argument is missing or undefined, not null.

ex-044-03 · Lesson 44

Fill in missing values

??= assigns only when the value is nullish.

ex-044-04 · Lesson 44

Defaults can use earlier parameters

Each default is evaluated when the function is called.

ex-045-01 · Lesson 45

Remove duplicates

A Set keeps only the first copy of each value.

ex-045-02 · Lesson 45

Fast membership checks

has answers 'is this in the collection?'.

ex-045-03 · Lesson 45

Count with a Map

get with a fallback plus set is the counting pattern.

ex-045-04 · Lesson 45

Objects as keys

A Map can use objects as keys; a plain object cannot.

ex-045-05 · Lesson 45

Convert to and from objects

Object.entries and Object.fromEntries bridge Maps and plain objects.

ex-046-01 · Lesson 46

Function scope

Each call has its own local variables.

ex-046-02 · Lesson 46

Block scope

let and const stay inside their block.

ex-046-03 · Lesson 46

Shadowing

The inner name hides the outer one inside its block.

ex-046-04 · Lesson 46

var ignores blocks

var is function-scoped; let is block-scoped.

ex-047-01 · Lesson 47

Walking the chain

Each lookup starts in the current scope and moves outward.

ex-047-02 · Lesson 47

Where it was written

A function sees the variables around its definition.

ex-047-03 · Lesson 47

Outer cannot see inner

Lookup only moves outward, never inward.

ex-047-04 · Lesson 47

A new environment per call

Every call gets fresh local variables linked to the same outer scope.

ex-048-01 · Lesson 48

Independent counters

Each factory call creates its own count.

ex-048-02 · Lesson 48

Function factory

The returned function remembers the rate it was made with.

ex-048-03 · Lesson 48

Private state

Only the returned methods can change the balance.

ex-048-04 · Lesson 48

The loop closure trap

var shares one variable; let gives each iteration its own.

ex-048-05 · Lesson 48

Variables, not snapshots

A closure reads the variable's current value when it runs.

ex-049-01 · Lesson 49

Function declarations are hoisted

You can call them before their line.

ex-049-02 · Lesson 49

var starts as undefined

The declaration is hoisted; the assignment is not.

ex-049-03 · Lesson 49

The temporal dead zone

let and const throw if used before their line.

ex-049-04 · Lesson 49

Function expressions are not hoisted as functions

With var, the name exists but is undefined.

ex-049-05 · Lesson 49

The TDZ is about time

A function may mention a const declared later, as long as it is called after.

ex-050-01 · Lesson 50

Call stack order

The caller waits until the called function returns.

ex-050-02 · Lesson 50

Measure the stack depth

Each nested call adds one context.

ex-050-03 · Lesson 50

Stack overflow

Calls without a stopping case fill the stack.

ex-050-04 · Lesson 50

How this is set

The call decides this for regular functions; arrows inherit it.

ex-050-05 · Lesson 50

Each context has its own variables

Recursive calls do not share locals.