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.
Your first output
console.log prints whatever you put between its parentheses. Each call prints one line, in the order the lines appear.
JavaScript calculates
Numbers and arithmetic operators outside quotes are calculated. Multiplication happens before addition, as in ordinary maths.
ex-001-03 · Lesson 1One 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 1JavaScript 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 2Order matters
Statements run from top to bottom, so the output appears in the same order as the lines.
ex-002-02 · Lesson 2Strings and numbers with +
With two numbers, + adds. If either side is a string, + joins text instead.
ex-002-03 · Lesson 2Remember a value
let creates a named value that can change. The right-hand side is worked out first, then stored.
A tiny greeting program
Constants hold values that do not change. Strings and numbers combine with + to build sentences.
ex-003-01 · Lesson 3Expressions produce values
Each console.log receives the value of an expression. Precedence and parentheses change the grouping.
ex-003-02 · Lesson 3Statements do work
Declarations and assignments are statements. The final value of total depends on each statement running in order.
ex-003-03 · Lesson 3Comments are ignored
Comments never run. A commented-out console.log prints nothing.
ex-003-04 · Lesson 3A 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 4Several values in one log
Commas separate values; console.log prints them with a space between.
ex-004-02 · Lesson 4Log levels
warn and error stand out from ordinary log lines. The academy console colours them, as browser tools do.
ex-004-03 · Lesson 4Tables 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 4Trace 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 5A 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 5A TypeError
price holds a number. Adding () tries to call it as a function, which numbers cannot do.
ex-005-03 · Lesson 5A 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 5Investigate 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 6let 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 6A 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 6Assigning to a const
Assigning to a const stops the program with a TypeError. Everything before that line has already run.
ex-006-04 · Lesson 6Names that explain themselves
Both programs compute the same thing. The second one can be read without any comments.
ex-007-01 · Lesson 7Three ways to build a message
+ needs explicit spaces; a template literal reads like the final text.
ex-007-02 · Lesson 7Useful string methods
Each method returns a new string or a value about the string. The original stays the same.
ex-007-03 · Lesson 7Quotes, 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 7When + 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 8Arithmetic operators
The six operators cover most calculations. % gives the remainder, ** the power.
ex-008-02 · Lesson 8Floating-point surprises
Binary decimals cause tiny errors. Round for display, or work in whole cents.
ex-008-03 · Lesson 8The Math toolbox
Math methods round, compare and pick numbers.
ex-008-04 · Lesson 8NaN and Infinity
Some operations have no normal numeric result. Check with Number.isNaN before showing a value.
ex-009-01 · Lesson 9Booleans from comparisons
Comparisons answer yes/no questions with true or false.
ex-009-02 · Lesson 9undefined versus null
undefined appears when nothing was assigned; null is assigned on purpose.
ex-009-03 · Lesson 9Truthy and falsy
Boolean(x) shows how a value behaves in a condition. Only six values are falsy.
ex-009-04 · Lesson 9When 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 10typeof every kind of value
typeof returns a string naming the type. Note the two quirks: null and arrays are "object".
ex-010-02 · Lesson 10Explicit conversion
Number, String and Boolean convert on purpose.
ex-010-03 · Lesson 10parseInt 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 10Implicit coercion
Arithmetic operators other than + convert text to numbers; + joins if either side is text.
ex-011-01 · Lesson 11The comparison operators
Each comparison produces true or false.
ex-011-02 · Lesson 11Strict versus loose equality
== converts types first; === never does.
ex-011-03 · Lesson 11Comparing strings
Strings compare by character codes. Capitals sort before lowercase letters.
ex-011-04 · Lesson 11Arrays compare by reference
Two arrays with the same contents are still two different arrays.
ex-012-01 · Lesson 12A truth table
Every combination of two booleans with && and ||.
ex-012-02 · Lesson 12Combining real rules
Parentheses make mixed && and || rules match the sentence.
ex-012-03 · Lesson 12Short-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 13if and else
One of the two blocks always runs.
ex-013-02 · Lesson 13An else if chain
Only the first matching branch runs, so the thresholds go from highest to lowest.
ex-013-03 · Lesson 13When the order is wrong
The first condition is too general, so the later ones can never run.
ex-013-04 · Lesson 13Check the invalid cases first
Handling bad input first keeps the main calculation simple.
ex-014-01 · Lesson 14switch with break
Exactly one case runs because each ends with break.
ex-014-02 · Lesson 14Missing break: fall-through
Without break, execution continues into the next cases.
ex-014-03 · Lesson 14Grouping cases on purpose
Several case labels can share one block.
ex-014-04 · Lesson 14The conditional operator
A ternary chooses between two values inside an expression.
ex-015-01 · Lesson 15Parking fee rules
Named constants keep the rules readable and easy to change.
ex-015-02 · Lesson 15Testing the boundaries
Checking just below, at and above the limit catches off-by-one mistakes.
ex-015-03 · Lesson 15Quiz result with reasons
Each outcome prints a specific reason.
ex-015-04 · Lesson 15Specific feedback
Checking rules separately lets the program say exactly what is missing.
ex-016-01 · Lesson 16Counting up
The counter starts at 1 and increases until the condition is false.
ex-016-02 · Lesson 16Counting down and stepping
The update can subtract, or add more than one.
ex-016-03 · Lesson 16Looping over an array by index
Indexes run from 0 to length - 1.
ex-016-04 · Lesson 16for...of for each value
When you need values rather than positions, for...of is shorter.
ex-017-01 · Lesson 17Until a goal is reached
The number of months is the result, not the input.
ex-017-02 · Lesson 17Halving until small
Each pass changes the value the condition checks.
ex-017-03 · Lesson 17do...while runs at least once
Even when the condition is false at the start, the body runs one time.
ex-017-04 · Lesson 17Stopping at a sentinel
The loop reads values until it finds the stop marker.
ex-018-01 · Lesson 18break ends a search
Once the item is found there is no need to look further.
ex-018-02 · Lesson 18continue skips items
Cancelled orders are skipped without nesting the rest of the body.
ex-018-03 · Lesson 18continue in a counting loop
The update i++ still runs after continue.
ex-018-04 · Lesson 18A flag instead of break
A condition in the loop header can replace break.
ex-019-01 · Lesson 19Labelling seats
The outer loop picks the row; the inner loop picks the seat number.
ex-019-02 · Lesson 19A star triangle
The inner loop's length depends on the outer counter.
ex-019-03 · Lesson 19Counting inner iterations
The inner body runs outer × inner times.
ex-019-04 · Lesson 19Reading a grid
grid[row][col] reaches each cell of an array of arrays.
ex-020-01 · Lesson 20Total and average
An accumulator gives the total; dividing by the count gives the average.
ex-020-02 · Lesson 20Counting matches
A counter only increases when the condition is true.
ex-020-03 · Lesson 20Minimum and maximum together
Start from the first value so negative data works.
ex-020-04 · Lesson 20A number problem
A while loop takes digits off a number one at a time.
ex-021-01 · Lesson 21Declare once, call many times
The body runs each time the function is called.
ex-021-02 · Lesson 21A function expression
A function can be stored in a const like any other value.
ex-021-03 · Lesson 21Declarations are hoisted
A declaration can be called before the line that defines it.
ex-021-04 · Lesson 21Functions are values
Printing a function shows the function, not its result.
ex-022-01 · Lesson 22One parameter, many calls
Each call fills name with a different argument.
ex-022-02 · Lesson 22Order matters
Arguments fill parameters by position.
ex-022-03 · Lesson 22Default and missing values
A default replaces undefined, and only undefined.
ex-022-04 · Lesson 22Any number of arguments
...prices collects all arguments into an array.
ex-023-01 · Lesson 23Use the returned value
The call becomes its return value.
ex-023-02 · Lesson 23Printing is not returning
A function that only logs gives back undefined.
ex-023-03 · Lesson 23Early return
return stops the function, so later lines do not run.
ex-023-04 · Lesson 23Returning several values
An object groups related results into one return value.
ex-024-01 · Lesson 24Three ways to write one function
Declaration, expression and arrow give the same result.
ex-024-02 · Lesson 24Block bodies need return
Braces turn off the automatic return.
ex-024-03 · Lesson 24Arrows as callbacks
Short arrows are passed straight into array methods.
ex-024-04 · Lesson 24Returning an object
Wrap an object literal in parentheses after =>.
ex-025-01 · Lesson 25A small pipeline
Each helper does one job; the main function connects them.
ex-025-02 · Lesson 25Validation returns a result
A validator returns an object instead of printing.
ex-025-03 · Lesson 25Testing each piece
A tiny check function tests helpers one by one.
ex-025-04 · Lesson 25Configuration as a parameter
Passing settings in makes functions reusable for other shops.
ex-026-01 · Lesson 26Create and read an array
Indexes start at 0; length counts the elements.
ex-026-02 · Lesson 26The last element
length - 1 and at(-1) both reach the end.
ex-026-03 · Lesson 26Changing an element
Assigning to an index replaces that element, even in a const array.
ex-026-04 · Lesson 26Calculating with elements
Elements are ordinary values, so you can calculate with them.
ex-027-01 · Lesson 27Working at the end
push adds, pop removes and returns the removed element.
ex-027-02 · Lesson 27Working at the start
unshift adds to the front; shift serves the front of a queue.
ex-027-03 · Lesson 27Removing from the middle
splice changes the array and returns what it removed.
ex-027-04 · Lesson 27slice and concat do not mutate
The original stays the same; a new array is returned.
ex-028-01 · Lesson 28Searching by value
includes answers yes/no; indexOf gives a position.
ex-028-02 · Lesson 28Searching by a rule
find returns the element; findIndex returns its position.
ex-028-03 · Lesson 28Sorting numbers correctly
Default sort compares text; a - b compares numbers.
ex-028-04 · Lesson 28Sorting objects by a property
The compare function reads the property to compare.
ex-029-01 · Lesson 29Three loops, one result
Classic for, for...of and forEach can produce the same output.
ex-029-02 · Lesson 29Index and value together
entries() with destructuring gives both.
ex-029-03 · Lesson 29Looping over objects
Each element is an object; read its properties.
ex-029-04 · Lesson 29Strings are iterable
for...of visits each character.
ex-030-01 · Lesson 30Add and list
A counter makes ids unique; printList only reads.
ex-030-02 · Lesson 30Update by id
find returns the object itself, so changing it updates the collection.
ex-030-03 · Lesson 30Remove by id
findIndex locates the item; splice removes it.
ex-030-04 · Lesson 30Summarise the collection
A summary function reads the state and returns numbers.
ex-031-01 · Lesson 31Doing something for each element
The callback runs once per element.
ex-031-02 · Lesson 31Passing a named function
Pass the function itself, without brackets.
ex-031-03 · Lesson 31Updating an outer variable
A side effect: the callback adds to a total declared outside.
ex-031-04 · Lesson 31Element, index and array
The third argument is the array itself.
ex-032-01 · Lesson 32Transform numbers
One output for every input; the original stays the same.
ex-032-02 · Lesson 32Objects to display strings
map turns data into lines to show.
ex-032-03 · Lesson 32A block body needs return
Without return, every element becomes undefined.
ex-032-04 · Lesson 32New objects, original untouched
Spread copies each object and adds a property.
ex-033-01 · Lesson 33Keep what passes
filter returns a new, shorter (or equal) array.
ex-033-02 · Lesson 33Filtering objects with two conditions
Combine conditions inside the predicate.
ex-033-03 · Lesson 33Named predicates
Small named tests make filters readable.
ex-033-04 · Lesson 33some and every
Yes/no questions about the whole list.
ex-034-01 · Lesson 34Summing with reduce
The accumulator starts at 0 and grows.
ex-034-02 · Lesson 34Finding the maximum
The accumulator keeps the best value seen so far.
ex-034-03 · Lesson 34Counting per category
The accumulator is an object of counts.
ex-034-04 · Lesson 34Totals per group
Grouping and summing in one pass.
ex-035-01 · Lesson 35Filter, then map
Keep the paid orders, then turn them into labels.
ex-035-02 · Lesson 35Top three
Sort, slice, then map.
ex-035-03 · Lesson 35Ending with reduce
A pipeline can end with one summary value.
ex-035-04 · Lesson 35Named steps
Small named functions make the pipeline read like requirements.
ex-036-01 · Lesson 36Create and read
Dot notation reads a property; console.log shows the whole object.
ex-036-02 · Lesson 36Update, add and delete
Objects change in place, even with const.
ex-036-03 · Lesson 36Shorthand properties
When a variable has the same name as the key, write it once.
ex-036-04 · Lesson 36Missing properties
A missing property is undefined; going deeper throws.
ex-037-01 · Lesson 37Reading a key from a variable
Brackets evaluate the expression inside them.
ex-037-02 · Lesson 37Computed keys
The key name comes from a variable.
ex-037-03 · Lesson 37Looping over an object
Object.entries gives pairs for a for...of loop.
ex-037-04 · Lesson 37Methods and this
A method reads the object's own data through this.
ex-038-01 · Lesson 38Reading nested paths
Each . or [ ] moves one level deeper.
ex-038-02 · Lesson 38Updating nested values
Assign at the end of a path.
ex-038-03 · Lesson 38Looping over nested arrays
Outer loop over orders, inner loop over items.
ex-038-04 · Lesson 38Nested data as JSON
JSON.stringify shows structure; JSON.parse reads it back.
ex-039-01 · Lesson 39Primitives are copied
Changing y does not change x.
ex-039-02 · Lesson 39Objects are shared
Two names, one object.
ex-039-03 · Lesson 39Shallow copies share nested objects
Spread copies the outer level only.
ex-039-04 · Lesson 39Deep copies and equality
structuredClone copies everything; === compares references.
ex-040-01 · Lesson 40Entities and links
Loans link a member and a book by id.
ex-040-02 · Lesson 40A factory with defaults and validation
Every created object has the same shape.
ex-040-03 · Lesson 40Derive, do not duplicate
Line totals and the order total are calculated, never stored.
ex-040-04 · Lesson 40One status instead of many booleans
A single status cannot contradict itself.
ex-041-01 · Lesson 41Unpack an object
Each name in the braces becomes a variable holding that property.
ex-041-02 · Lesson 41Unpack an array
Array destructuring works by position, and an empty slot skips one.
ex-041-03 · Lesson 41Rename and default
A colon renames; = gives a fallback for undefined values.
ex-041-04 · Lesson 41Destructured parameters
Unpacking in the parameter list shows exactly which properties a function needs.
ex-041-05 · Lesson 41Swap two variables
Destructuring an array literal swaps values without a temporary variable.
ex-042-01 · Lesson 42Combine arrays
Spread places each item of each array into the new array.
ex-042-02 · Lesson 42Copy and update an object
Later properties override earlier ones.
ex-042-03 · Lesson 42Rest parameters
Rest collects any number of arguments into a real array.
ex-042-04 · Lesson 42Omit fields with object rest
Destructure the fields to drop and keep the rest.
ex-042-05 · Lesson 42Spread is shallow
Nested objects are shared between the original and the copy.
ex-043-01 · Lesson 43Read nested data safely
?. returns undefined instead of throwing.
ex-043-02 · Lesson 43Add a fallback
?? supplies a value when the chain gives undefined.
ex-043-03 · Lesson 43Optional method call
?.() calls a function only if it exists.
ex-043-04 · Lesson 43Optional indexing
?.[ ] reads an index only when the array exists.
ex-044-01 · Lesson 44|| versus ??
Only ?? keeps valid falsy values.
ex-044-02 · Lesson 44Default parameters
Defaults apply when the argument is missing or undefined, not null.
ex-044-03 · Lesson 44Fill in missing values
??= assigns only when the value is nullish.
ex-044-04 · Lesson 44Defaults can use earlier parameters
Each default is evaluated when the function is called.
ex-045-01 · Lesson 45Remove duplicates
A Set keeps only the first copy of each value.
ex-045-02 · Lesson 45Fast membership checks
has answers 'is this in the collection?'.
ex-045-03 · Lesson 45Count with a Map
get with a fallback plus set is the counting pattern.
ex-045-04 · Lesson 45Objects as keys
A Map can use objects as keys; a plain object cannot.
ex-045-05 · Lesson 45Convert to and from objects
Object.entries and Object.fromEntries bridge Maps and plain objects.
ex-046-01 · Lesson 46Function scope
Each call has its own local variables.
ex-046-02 · Lesson 46Block scope
let and const stay inside their block.
ex-046-03 · Lesson 46Shadowing
The inner name hides the outer one inside its block.
ex-046-04 · Lesson 46var ignores blocks
var is function-scoped; let is block-scoped.
ex-047-01 · Lesson 47Walking the chain
Each lookup starts in the current scope and moves outward.
ex-047-02 · Lesson 47Where it was written
A function sees the variables around its definition.
ex-047-03 · Lesson 47Outer cannot see inner
Lookup only moves outward, never inward.
ex-047-04 · Lesson 47A new environment per call
Every call gets fresh local variables linked to the same outer scope.
ex-048-01 · Lesson 48Independent counters
Each factory call creates its own count.
ex-048-02 · Lesson 48Function factory
The returned function remembers the rate it was made with.
ex-048-03 · Lesson 48Private state
Only the returned methods can change the balance.
ex-048-04 · Lesson 48The loop closure trap
var shares one variable; let gives each iteration its own.
ex-048-05 · Lesson 48Variables, not snapshots
A closure reads the variable's current value when it runs.
ex-049-01 · Lesson 49Function declarations are hoisted
You can call them before their line.
ex-049-02 · Lesson 49var starts as undefined
The declaration is hoisted; the assignment is not.
ex-049-03 · Lesson 49The temporal dead zone
let and const throw if used before their line.
ex-049-04 · Lesson 49Function expressions are not hoisted as functions
With var, the name exists but is undefined.
ex-049-05 · Lesson 49The TDZ is about time
A function may mention a const declared later, as long as it is called after.
ex-050-01 · Lesson 50Call stack order
The caller waits until the called function returns.
ex-050-02 · Lesson 50Measure the stack depth
Each nested call adds one context.
ex-050-03 · Lesson 50Stack overflow
Calls without a stopping case fill the stack.
ex-050-04 · Lesson 50How this is set
The call decides this for regular functions; arrows inherit it.
ex-050-05 · Lesson 50Each context has its own variables
Recursive calls do not share locals.