Use JavaScript to put the word running into #out.
Acceptance criteria
- 1.#out should show running.
- 2.Put the text on the page with JavaScript.
Pick a result and write the JavaScript that makes it. Every exercise here runs without an account.
207 shown
Use JavaScript to put the word running into #out.
Exercises: What is JavaScriptdocument.querySelector('#out').textContent = "running";querySelector finds the element with the id out, and textContent replaces the text inside it.
Give one variable the number 10, then the text "ten". Show its final type in #out.
JavaScript Features exerciseslet value = 10;
value = "ten";
document.querySelector('#out').textContent = typeof value;A JavaScript variable has no fixed type. After the second line it holds text, so typeof gives string.
Store the word complete in a variable. Show the variable in #out.
JavaScript Syntax exercisesconst state = "complete";
document.querySelector('#out').textContent = state;const creates the variable, and the second statement reads it to fill the page.
Find the element with the id out and set its text to connected.
Exercises: How to Add JavaScriptdocument.querySelector("#out").textContent = "connected";The script can find #out because the element already exists when the script runs.
document.querySelector('#out').textContent = "plain";textContent writes the value as text, so tags in it would show as characters.
Write a // comment that says what your code does. Then show the word documented in #out.
JavaScript Comments exercises// Show the current state
document.querySelector('#out').textContent = "documented";The browser skips everything after // on that line. Only the next line runs.
Declare a variable named score with let and set it to 42. Show it in #out.
JavaScript Variables exerciseslet score = 42;
document.querySelector('#out').textContent = score;let score = 42 creates the variable, and reading score gives 42.
Use typeof to show the type of the value 7 in #out.
JavaScript Data Types exercisesdocument.querySelector('#out').textContent = typeof 7;Every number in JavaScript, whole or decimal, has the type number.
document.querySelector('#out').textContent = 12 + 8;Without quotes 12 and 8 are numbers, so + adds them. With quotes it would join them into 128.
Set a variable to first, then change it to second. Show its final value in #out.
JavaScript Statements exerciseslet label = "first";
label = "second";
document.querySelector('#out').textContent = label;Statements run from top to bottom, so the last value set is the one shown.
If 3 * 7 equals 21, show correct in #out. Otherwise show wrong.
JavaScript Expressions exercisesdocument.querySelector('#out').textContent = (3 * 7 === 21) ? "correct" : "wrong";3 * 7 works out to 21, the comparison gives true, and true picks correct.
Declare a constant holding the word fixed. Show it in #out.
JavaScript Keywords exercisesconst value = "fixed";
document.querySelector('#out').textContent = value;const is a keyword: a word JavaScript keeps for itself, here to create a constant.
Store the word named in a variable called userStatus. Show it in #out.
JavaScript Identifiers exercisesconst userStatus = "named";
document.querySelector('#out').textContent = userStatus;userStatus says what the value is for, which a name like x would not.
Store the word matched in a variable called userName. Show it in #out.
JavaScript Case Sensitivity exercisesconst userName = "matched";
document.querySelector('#out').textContent = userName;JavaScript compares every letter, so only userName with a capital N finds the variable.
Write one statement that stores the word first and a second that shows the word terminated in #out. End both with a semicolon.
JavaScript Semicolons exercisesconst a = "first";
document.querySelector('#out').textContent = "terminated";A semicolon marks where one statement stops and the next one starts.
Inside an if block, store the word grouped in a variable and show it in #out. Use a condition that is true.
JavaScript Code Blocks exercisesconst on = true;
if (on) {
const note = "grouped";
document.querySelector('#out').textContent = note;
}The braces make the two statements one group, so both run when the condition is true.
Set age to 20. If age is 18 or more, show adult in #out.
JavaScript if Statement exercisesconst age = 20;
if (age >= 18) {
document.querySelector('#out').textContent = "adult";
}20 >= 18 is true, so the block runs. With an age of 15 nothing would be shown.
Set score to 87. Use if, else if and else to show A in #result for 90 or more, B for 80 to 89, or C below 80.
JavaScript if else Statement exercisesconst score = 87;
const result = document.getElementById('result');
if (score >= 90) {
result.textContent = 'A';
} else if (score >= 80) {
result.textContent = 'B';
} else {
result.textContent = 'C';
}Set score to 85. Show A in #out for 90 or more, B for 80 or more, otherwise C.
JavaScript else if Statement exercisesconst score = 85;
if (score >= 90) {
document.querySelector('#out').textContent = "A";
} else if (score >= 80) {
document.querySelector('#out').textContent = "B";
} else {
document.querySelector('#out').textContent = "C";
}85 is not 90 or more, so the first block is skipped. It is 80 or more, so B is shown.
Set day to "Monday". Use a switch to show start in #out for Monday and other for any other day.
JavaScript switch Statement exercisesconst day = "Monday";
switch (day) {
case "Monday":
document.querySelector('#out').textContent = "start";
break;
default:
document.querySelector('#out').textContent = "other";
}day matches case "Monday", so start is shown and break leaves the switch.
Set age to 20. Use ? : to show adult in #out when age is 18 or more, otherwise minor.
JavaScript Ternary Operator exercisesconst age = 20;
document.querySelector('#out').textContent = age >= 18 ? "adult" : "minor";20 >= 18 is true, so the value before the colon is used.
Use a for loop to append 5 <li> elements to #list, with text "Item 1" through "Item 5".
JavaScript for Loop exercisesconst list = document.getElementById('list');
for (let i = 1; i <= 5; i++) {
const item = document.createElement('li');
item.textContent = 'Item ' + i;
list.appendChild(item);
}Use a while loop to count 1, 2, 3, 4. Show them joined by commas in #out.
JavaScript while Loop exercisesconst parts = [];
let i = 1;
while (i <= 4) {
parts.push(i);
i++;
}
document.querySelector('#out').textContent = parts.join(",");The loop runs while i is 4 or less. Each pass adds i to the list and raises it by one.
Write a do...while loop whose condition is false. Count how many times its body runs and show the count in #out.
JavaScript do while Loop exerciseslet runs = 0;
do {
runs++;
} while (false);
document.querySelector('#out').textContent = runs;do...while checks its condition after the body, so the body runs once even when it is false.
Loop from 1 to 10 and stop at the first number that divides by 4. Show that number in #out.
JavaScript break Statement exerciseslet found = 0;
for (let i = 1; i <= 10; i++) {
if (i % 4 === 0) {
found = i;
break;
}
}
document.querySelector('#out').textContent = found;1, 2 and 3 leave a remainder. At 4 the remainder is 0, so break ends the loop there.
Add the numbers 1 to 6 but skip 4 with continue. Show the total in #out.
JavaScript continue Statement exerciseslet total = 0;
for (let i = 1; i <= 6; i++) {
if (i === 4) continue;
total += i;
}
document.querySelector('#out').textContent = total;1 + 2 + 3 + 5 + 6 is 17. At 4, continue skips the line that adds.
Loop over { name: "John", age: 30, city: "London" } with for...in. Show the property names joined by dashes in #out.
JavaScript for in Loop exercisesconst person = { name: "John", age: 30, city: "London" };
const keys = [];
for (const key in person) {
keys.push(key);
}
document.querySelector('#out').textContent = keys.join("-");for...in visits the names name, age and city, and join puts a dash between them.
Add every number in [10, 20, 30, 40] with for...of. Show the total in #out.
JavaScript for of Loop exercisesconst numbers = [10, 20, 30, 40];
let total = 0;
for (const number of numbers) {
total += number;
}
document.querySelector('#out').textContent = total;Each pass takes the next number and adds it: 10, then 30, then 60, then 100.
Put a loop of 4 turns inside a loop of 3 turns. Count how many times the inner code runs and show the count in #out.
JavaScript Nested Loops exerciseslet count = 0;
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 4; j++) {
count++;
}
}
document.querySelector('#out').textContent = count;For each of the 3 outer turns the inner loop runs 4 times, and 3 * 4 is 12.
Write a function that returns the word Hello. Call it and show the result in #out.
JavaScript Functions exercisesfunction greet() {
return "Hello";
}
document.querySelector('#out').textContent = greet();The function runs when it is called, and the call is replaced by what it returns.
Declare a function named square that returns a number times itself. Show the square of 9 in #out.
JavaScript Function Declarations exercisesfunction square(n) {
return n * n;
}
document.querySelector('#out').textContent = square(9);n is 9 inside the function, so it returns 9 * 9.
Store a function that doubles a number in a variable. Show the result for 16 in #out.
JavaScript Function Expressions exercisesconst double = function (n) {
return n * 2;
};
document.querySelector('#out').textContent = double(16);The variable holds the function, so double(16) runs it with n set to 16.
Write a function that joins a name and a city with the word from. Call it with "Ada" and "London", so #out shows Ada from London.
JavaScript Function Parameters exercisesfunction where(name, city) {
return name + " from " + city;
}
document.querySelector('#out').textContent = where("Ada", "London");The first value goes to the first parameter and the second to the second.
Write a function that returns Hello and a name, where the name is friend by default. Call it with no value and show the result in #out.
JavaScript Default Parameters exercisesfunction greet(name = "friend") {
return "Hello " + name;
}
document.querySelector('#out').textContent = greet();No value was passed, so the parameter takes its default, friend.
Write a function that uses a rest parameter to add all the values it is given. Show the result for 1, 2, 3 and 4 in #out.
JavaScript Rest Parameters exercisesfunction addAll(...numbers) {
let total = 0;
for (const n of numbers) total += n;
return total;
}
document.querySelector('#out').textContent = addAll(1, 2, 3, 4);...numbers gathers 1, 2, 3 and 4 into one array, and the loop adds them.
Write a function that returns the sum of two numbers. Show the result for 3 and 4 in #out.
JavaScript return Statement exercisesfunction add(a, b) {
return a + b;
}
document.querySelector('#out').textContent = add(3, 4);The function returns 3 + 4, so the call has the value 7.
Write an arrow function that doubles a number. Show the result for 25 in #out.
JavaScript Arrow Functions exercisesconst double = (n) => {
return n * 2;
};
document.querySelector('#out').textContent = double(25);n is 25, so n * 2 gives 50.
Write a function that takes another function and returns what it returns. Pass it one that returns done, and show the result in #out.
JavaScript Callback Functions exercisesfunction run(callback) {
return callback();
}
document.querySelector('#out').textContent = run(function () {
return "done";
});run receives the function as callback and calls it, so it returns done.
Use map to add 20 percent to each price in [100, 200]. Show the results joined by commas in #out.
JavaScript Higher Order Functions exercisesdocument.querySelector('#out').textContent = [100, 200].map(p => p * 1.2).join(",");map calls the function once for each price: 100 * 1.2 is 120 and 200 * 1.2 is 240.
Write a function that calls itself to count down from 3 to 1. Show the numbers joined by dashes in #out.
JavaScript Recursion exercisesfunction down(n, acc) {
if (n === 0) return acc.join("-");
acc.push(n);
return down(n - 1, acc);
}
document.querySelector('#out').textContent = down(3, []);Each call handles one number and calls itself with the next. At 0 it stops and the numbers are joined.
Write a function that is called at once and returns 6 times 7. Store the answer and show it in #out.
JavaScript IIFE exercisesconst answer = (function () {
return 6 * 7;
})();
document.querySelector('#out').textContent = answer;The last brackets call the function straight away, so answer holds 42.
Given const person = { name: "Ada" }, write a function that returns "Hello " and this.name. Run it with call so #out shows Hello Ada.
JavaScript call, apply and bind exercisesconst person = { name: "Ada" };
function greet() {
return "Hello " + this.name;
}
document.querySelector('#out').textContent = greet.call(person);greet.call(person) runs greet with this set to person, so this.name is Ada.
Write a function that adds two numbers and changes nothing else. Call it twice with 2 and 3, and show both results joined by a comma in #out.
JavaScript Pure Functions exercisesfunction add(a, b) {
return a + b;
}
document.querySelector('#out').textContent = add(2, 3) + "," + add(2, 3);A pure function gives the same answer for the same values, so both calls give 5.
Store My Site in a variable outside any function. Write a function that returns it, and show the result in #out.
JavaScript Scope exercisesconst siteName = "My Site";
function show() {
return siteName;
}
document.querySelector('#out').textContent = show();The variable is not inside show, so JavaScript looks outside and finds it.
Declare a let variable inside braces. Outside the braces, show its typeof in #out.
JavaScript Block Scope exercises{
let message = "inside";
}
document.querySelector('#out').textContent = typeof message;let only exists inside its block. Outside, the name is unknown and typeof gives undefined.
Show the typeof of a var variable before the line that gives it the value 5. #out should show undefined.
JavaScript Hoisting exercisesdocument.querySelector('#out').textContent = typeof count;
var count = 5;The declaration moves to the top but the value does not, so the variable is undefined until its line runs.
Declare a let variable holding ready. Read it on the next line and show it in #out.
JavaScript Temporal Dead Zone exerciseslet state = "ready";
document.querySelector('#out').textContent = state;A let variable cannot be used before its line. After that line it works normally.
Write a function that returns a counting function. Call the counter three times and show the results joined by commas in #out.
JavaScript Closures exercisesfunction makeCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const c = makeCounter();
document.querySelector('#out').textContent = [c(), c(), c()].join(",");The inner function keeps its own link to count, so the count survives between calls.
Make an object with the name Ada and a greet method that returns "Hello " and this.name. Show what greet returns in #out.
JavaScript this Keyword exercisesconst person = {
name: "Ada",
greet: function () {
return "Hello " + this.name;
}
};
document.querySelector('#out').textContent = person.greet();greet is called on person, so this.name is Ada.
Create an array holding "Apple", "Banana" and "Mango". Show how many items it has in #out.
JavaScript Arrays exercisesconst fruits = ["Apple", "Banana", "Mango"];
document.querySelector('#out').textContent = fruits.length;length is the number of items, so an array of three fruits gives 3.
Create the array ["Apple", "Banana", "Mango"]. Show its first item in #out.
JavaScript Array Access exercisesconst fruits = ["Apple", "Banana", "Mango"];
document.querySelector('#out').textContent = fruits[0];The first item is at position 0, so fruits[0] is Apple.
Start with the array ["Ada"]. Push "Grace" and "Alan" onto it. Show the result joined by commas in #out.
JavaScript Array push and pop exercisesconst list = ["Ada"];
list.push("Grace", "Alan");
document.querySelector('#out').textContent = list.join(",");push changes the same array, so list ends up holding all three names.
Copy the middle two values out of ["a", "b", "c", "d"] with slice. Show them joined by commas in #out.
JavaScript Array slice and splice exercisesconst list = ["a", "b", "c", "d"];
document.querySelector('#out').textContent = list.slice(1, 3).join(",");slice(1, 3) copies positions 1 and 2, which are b and c. The list itself does not change.
Combine [1, 2] and [3, 4] with concat. Show the result joined by commas in #out.
JavaScript Array concat and join exercisesconst a = [1, 2];
const b = [3, 4];
document.querySelector('#out').textContent = a.concat(b).join(",");concat returns a new array holding both, and join puts a comma between the values.
Find the position of "Banana" in ["Apple", "Banana", "Mango"]. Show it in #out.
JavaScript Array Search exercisesconst fruits = ["Apple", "Banana", "Mango"];
document.querySelector('#out').textContent = fruits.indexOf("Banana");Banana is the second item, and positions start at 0, so indexOf gives 1.
Go through ["a", "b", "c"] with forEach, adding each value and a dash to some text. Show a-b-c- in #out.
JavaScript Array forEach exercisesconst list = ["a", "b", "c"];
let text = "";
list.forEach(item => {
text += item + "-";
});
document.querySelector('#out').textContent = text;forEach runs the function once for each value. Each run adds one letter and one dash.
Use map to double each number in [1, 2, 3]. Show the result joined by commas in #out.
JavaScript Array map exercisesconst numbers = [1, 2, 3];
document.querySelector('#out').textContent = numbers.map(n => n * 2).join(",");map builds a new array from the returned values: 1 becomes 2, 2 becomes 4, 3 becomes 6.
Use filter to keep the even numbers in [1, 2, 3, 4, 5, 6]. Show them joined by commas in #out.
JavaScript Array filter exercisesconst numbers = [1, 2, 3, 4, 5, 6];
document.querySelector('#out').textContent = numbers.filter(n => n % 2 === 0).join(",");n % 2 is the remainder after dividing by 2. It is 0 only for 2, 4 and 6.
Use reduce to add up [10, 20, 30]. Show the total in #out.
JavaScript Array reduce exercisesconst numbers = [10, 20, 30];
document.querySelector('#out').textContent = numbers.reduce((sum, n) => sum + n, 0);The total starts at 0. Each number is added to it: 0 + 10, 10 + 20, 30 + 30.
Use find to get the first number above 4 in [1, 8, 3, 12]. Show it in #out.
JavaScript Array find exercisesconst numbers = [1, 8, 3, 12];
document.querySelector('#out').textContent = numbers.find(n => n > 4);find stops at 8, the first number above 4. It never reaches 12.
Use some to check whether any number in [1, 8, 3] is above 5. Show the answer, true or false, in #out.
JavaScript Array some and every exercisesconst numbers = [1, 8, 3];
document.querySelector('#out').textContent = numbers.some(n => n > 5);8 is above 5, and one match is enough, so some returns true.
Sort [10, 1, 5] from smallest to largest. Show the result joined by commas in #out.
JavaScript Array sort exercisesconst numbers = [10, 1, 5];
document.querySelector('#out').textContent = numbers.sort((a, b) => a - b).join(",");a - b is negative when a is smaller, which tells sort to put a first.
Flatten [1, [2, 3], [4]] with flat. Show the result joined by commas in #out.
JavaScript Array flat exercisesconst nested = [1, [2, 3], [4]];
document.querySelector('#out').textContent = nested.flat().join(",");flat moves 2, 3 and 4 out of their inner arrays into one array.
Create a person object with the name "Ada" and the age 36. Show the name in #out by reading it from the object.
JavaScript Objects exercisesconst person = { name: "Ada", age: 36 };
document.querySelector('#out').textContent = person.name;person.name looks up the value stored under name.
Make an object with the name "Ada" and a greet method that says Hello and the name. Show what greet returns in #out.
JavaScript Object Methods exercisesconst person = {
name: "Ada",
greet() {
return "Hello " + this.name;
}
};
document.querySelector('#out').textContent = person.greet();greet belongs to person, so this.name inside it is Ada.
Show the property names of { name: "Ada", age: 36 } joined by commas in #out. Use Object.keys.
JavaScript Object keys and values exercisesconst person = { name: "Ada", age: 36 };
document.querySelector('#out').textContent = Object.keys(person).join(",");Object.keys gives ["name", "age"], and join turns it into text.
Take name and age out of { name: "Ada", age: 36 } with destructuring. Show Ada is 36 in #out.
JavaScript Destructuring exercisesconst person = { name: "Ada", age: 36 };
const { name, age } = person;
document.querySelector('#out').textContent = name + " is " + age;const { name, age } = person makes two variables from the two properties.
Copy { name: "Ada" } with spread and change the copy's name to Grace. Show the original's name in #out.
JavaScript Object Spread exercisesconst original = { name: "Ada" };
const copy = { ...original };
copy.name = "Grace";
document.querySelector('#out').textContent = original.name;Spread makes a new object, so changing the copy leaves the original as Ada.
Given const user = { name: "Ada" }, read user.address.city with optional chaining. Show the typeof of the result in #out.
JavaScript Optional Chaining exercisesconst user = { name: "Ada" };
document.querySelector('#out').textContent = typeof user.address?.city;address is missing, so ?. gives undefined instead of an error.
Given const settings = { volume: 0 }, use ?? to show the volume in #out, or 50 if there is none.
JavaScript Nullish Coalescing exercisesconst settings = { volume: 0 };
document.querySelector('#out').textContent = settings.volume ?? 50;0 is a real value, so ?? keeps it. || would have replaced it with 50.
Make an object with first "Ada" and last "Lovelace", and a fullName getter that joins them with a space. Show fullName in #out.
JavaScript Getters and Setters exercisesconst person = {
first: "Ada",
last: "Lovelace",
get fullName() {
return this.first + " " + this.last;
}
};
document.querySelector('#out').textContent = person.fullName;Reading fullName runs the getter, which joins the two names.
Turn { name: "Ada" } into JSON text and show it in #out.
JavaScript JSON exercisesconst person = { name: "Ada" };
document.querySelector('#out').textContent = JSON.stringify(person);JSON.stringify writes the object as text with double quotes round names and values.
Freeze { theme: "dark" }, then try to change theme to "light". Show theme in #out.
JavaScript Object freeze exercisesconst settings = Object.freeze({ theme: "dark" });
settings.theme = "light";
document.querySelector('#out').textContent = settings.theme;A frozen object ignores changes, so theme is still dark.
Write a Person constructor function that stores a name. Build one with the name Ada and show its name in #out.
JavaScript Object Constructors exercisesfunction Person(name) {
this.name = name;
}
document.querySelector('#out').textContent = new Person("Ada").name;new makes an empty object, runs Person with this set to it, and gives it back.
Read the text of the heading with the id title and show it in #out.
JavaScript DOM exercisesdocument.querySelector('#out').textContent = document.getElementById("title").textContent;Reading textContent gives Welcome, and setting #out's textContent shows it.
Read the text of the element with the class note and show it in #out.
JavaScript DOM Selectors exercisesdocument.querySelector('#out').textContent = document.querySelector(".note").textContent;querySelector(".note") finds the first element with that class.
Set the text of #box to Hello. Then read it back and show it in #out.
JavaScript DOM Content exercisesconst box = document.getElementById("box");
box.textContent = "Hello";
document.querySelector('#out').textContent = box.textContent;The box's text becomes Hello, and reading it gives the new text.
Use getAttribute to read the href of #link and show it in #out.
JavaScript DOM Attributes exercisesdocument.querySelector('#out').textContent = document.getElementById("link").getAttribute("href");getAttribute gives the value as written in the HTML, /about.
Set the colour of #demo to red with style. Then read it back and show it in #out.
JavaScript DOM Styles exercisesconst p = document.getElementById("demo");
p.style.color = "red";
document.querySelector('#out').textContent = p.style.color;Setting style.color writes the colour on the element, and reading it gives red.
Add the class active to #demo. Show its full class list in #out.
JavaScript classList exercisesconst p = document.getElementById("demo");
p.classList.add("active");
document.querySelector('#out').textContent = p.className;#demo already had note. add puts active after it and keeps both.
Create a paragraph and put it in #box. Show how many paragraphs the box holds in #out.
JavaScript Creating Elements exercisesconst p = document.createElement("p");
p.textContent = "New";
document.getElementById("box").append(p);
document.querySelector('#out').textContent = document.querySelectorAll("#box p").length;The new paragraph is not on the page until append adds it. Then the box holds one.
Add a list item saying Last to the end of #list. Show the text of the list's last item in #out.
JavaScript Inserting Elements exercisesconst li = document.createElement("li");
li.textContent = "Last";
document.getElementById("list").append(li);
document.querySelector('#out').textContent = document.getElementById("list").lastElementChild.textContent;append puts the item after First, so it becomes the last element.
Remove #demo from the page. Show how many paragraphs are left in #box in #out.
JavaScript Removing Elements exercisesdocument.getElementById("demo").remove();
document.querySelector('#out').textContent = document.querySelectorAll("#box p").length;remove takes the paragraph off the page, so none is left in the box.
Show the id of the element that holds #demo in #out.
JavaScript DOM Traversal exercisesdocument.querySelector('#out').textContent = document.getElementById("demo").parentElement.id;parentElement goes one step up, to the box.
Show how many paragraphs are on the page in #out. Do not count #out itself.
JavaScript DOM Collections exercisesdocument.querySelector('#out').textContent = document.querySelectorAll("p:not(#out)").length;The page has three paragraphs besides #out, and length counts them.
Show the value of the field with the id name in #out.
JavaScript Forms and Inputs exercisesdocument.querySelector('#out').textContent = document.getElementById("name").value;value holds what is in the field, which is Ada.
document.getElementById("btn").addEventListener("click", function () {
document.querySelector('#out').textContent = "Clicked";
});The function is kept and runs each time the button is clicked.
Count clicks on #btn in #out, but use the once option so only the first click counts.
JavaScript addEventListener exerciseslet count = 0;
document.getElementById("btn").addEventListener("click", function () {
count = count + 1;
document.querySelector('#out').textContent = String(count);
}, { once: true });once removes the listener after its first run, so later clicks do nothing.
When #btn is clicked, show the type of the event in #out.
JavaScript Event Object exercisesdocument.getElementById("btn").addEventListener("click", function (event) {
document.querySelector('#out').textContent = event.type;
});The browser passes the event to the function, and its type is click.
Show Down in #out when the mouse button is pressed on #box. Then send the box a mousedown event from code to test it.
JavaScript Mouse Events exercisesconst box = document.getElementById("box");
box.addEventListener("mousedown", function () {
document.querySelector('#out').textContent = "Down";
});
box.dispatchEvent(new MouseEvent("mousedown"));dispatchEvent fires the event from code, so the listener runs.
Show which key was pressed in #field in #out. Then send the field a keydown event for the key a to test it.
JavaScript Keyboard Events exercisesconst field = document.getElementById("field");
field.addEventListener("keydown", function (event) {
document.querySelector('#out').textContent = event.key;
});
field.dispatchEvent(new KeyboardEvent("keydown", { key: "a" }));The event carries key: "a", so event.key is a.
When #form is submitted, stop the reload and show the value of #name in #out. Then send the form a submit event to test it.
JavaScript Form Events exercisesconst form = document.getElementById("form");
form.addEventListener("submit", function (event) {
event.preventDefault();
document.querySelector('#out').textContent = document.getElementById("name").value;
});
form.dispatchEvent(new Event("submit", { cancelable: true }));preventDefault keeps the page in place, so the value can be read and shown.
Listen for clicks on #box and show box heard it in #out. A click on the button inside should reach it.
JavaScript Event Bubbling exercisesdocument.getElementById("box").addEventListener("click", function () {
document.querySelector('#out').textContent = "box heard it";
});The click starts at the button and bubbles up to the box, which hears it too.
Put one click listener on #list. Show the text of the item that was clicked in #out.
JavaScript Event Delegation exercisesdocument.getElementById("list").addEventListener("click", function (event) {
document.querySelector('#out').textContent = event.target.textContent;
});The click bubbles up to the list, and event.target says which item it came from.
When #link is clicked, stop it from opening and show stayed here in #out.
JavaScript preventDefault exercisesdocument.getElementById("link").addEventListener("click", function (event) {
event.preventDefault();
document.querySelector('#out').textContent = "stayed here";
});Following the link is the default action, and preventDefault cancels it.
Add a click listener to #btn that shows clicked, then remove it. Show removed in #out, and it should stay after a click.
JavaScript removeEventListener exercisesconst btn = document.getElementById("btn");
function handle() {
document.querySelector('#out').textContent = "clicked";
}
btn.addEventListener("click", handle);
btn.removeEventListener("click", handle);
document.querySelector('#out').textContent = "removed";The listener is gone, so a click changes nothing.
Show Ready in #out from inside a DOMContentLoaded listener.
JavaScript Page Load Events exercisesdocument.addEventListener("DOMContentLoaded", function () {
document.querySelector('#out').textContent = "Ready";
});
document.dispatchEvent(new Event("DOMContentLoaded"));The event fires when the HTML has been read, so every element can be found by then.
Listen for an event called itemAdded on #cart and show heard it in #out. Then fire that event.
JavaScript Custom Events exercisesconst cart = document.getElementById("cart");
cart.addEventListener("itemAdded", function () {
document.querySelector('#out').textContent = "heard it";
});
cart.dispatchEvent(new CustomEvent("itemAdded"));Your own event works like a click: the listener runs when the event is fired.
Add first to an array, then third from a timer of 0, then second. From the timer, show them joined by spaces in #out.
JavaScript Asynchronous exercisesconst order = [];
order.push("first");
setTimeout(function () {
order.push("third");
document.querySelector('#out').textContent = order.join(" ");
}, 0);
order.push("second");Even with a delay of 0 the timer waits for the other lines, so second is added before third.
Use setTimeout to show done in #out after 10 milliseconds.
JavaScript setTimeout exercisessetTimeout(function () {
document.querySelector('#out').textContent = "done";
}, 10);setTimeout keeps the function and runs it when the delay is over.
Use setInterval to count to 3, then stop it and show the count in #out.
JavaScript setInterval exerciseslet count = 0;
const id = setInterval(function () {
count = count + 1;
if (count === 3) {
clearInterval(id);
document.querySelector('#out').textContent = String(count);
}
}, 5);The function runs again and again until clearInterval stops it at 3.
Write a function that gives the name Ada to a callback after 5 milliseconds. Use it to show got Ada in #out.
JavaScript Async Callbacks exercisesfunction loadUser(callback) {
setTimeout(function () {
callback("Ada");
}, 5);
}
loadUser(function (name) {
document.querySelector('#out').textContent = "got " + name;
});The name is not ready at once, so the function hands it over later by calling the callback.
Make a promise that resolves with the name Ada after 5 milliseconds. Use then to show got Ada in #out.
JavaScript Promises exercisesconst promise = new Promise(function (resolve) {
setTimeout(function () {
resolve("Ada");
}, 5);
});
promise.then(function (name) {
document.querySelector('#out').textContent = "got " + name;
});resolve("Ada") finishes the promise, and then runs with Ada.
Start from a promise that resolves with 2. Multiply by 5 in one then, and show the result in #out from the next.
JavaScript Promise Chaining exercisesPromise.resolve(2)
.then(function (n) {
return n * 5;
})
.then(function (n) {
document.querySelector('#out').textContent = String(n);
});The first then returns 10, and the second receives it.
Make a promise that rejects with new Error("no network"). Catch it and show caught: no network in #out.
JavaScript Promise Errors exercisesPromise.reject(new Error("no network")).catch(function (error) {
document.querySelector('#out').textContent = "caught: " + error.message;
});catch receives the error, and its message is no network.
In an async function, await a promise that resolves with Ada. Show got Ada in #out.
JavaScript async and await exercisesasync function run() {
const name = await Promise.resolve("Ada");
document.querySelector('#out').textContent = "got " + name;
}
run();await pauses the function until the promise has a value.
In an async function, await a promise that rejects with new Error("no network"). Catch it and show caught: no network in #out.
JavaScript async Error Handling exercisesasync function run() {
try {
await Promise.reject(new Error("no network"));
} catch (error) {
document.querySelector('#out').textContent = "caught: " + error.message;
}
}
run();A rejected promise makes await throw, so catch runs.
Use Promise.all on promises that resolve with 1 and 2. Show both values joined by a comma in #out.
JavaScript Promise.all exercisesPromise.all([Promise.resolve(1), Promise.resolve(2)]).then(function (values) {
document.querySelector('#out').textContent = values.join(",");
});Promise.all waits for both and keeps their order, so the values are 1 and 2.
Write a function named fetch that resolves with an object whose json() resolves with { name: "Ada" }. Use it as fetch("/api/user") and show the name in #out.
JavaScript Fetch API exercisesfunction fetch(url) {
return Promise.resolve({
ok: true,
json: function () { return Promise.resolve({ name: "Ada" }); }
});
}
fetch("/api/user")
.then(function (response) {
return response.json();
})
.then(function (data) {
document.querySelector('#out').textContent = data.name;
});The first step gives the response, json() reads the data, and the second step uses it.
Add timer to an array from a setTimeout of 0, then add sync below it. From the timer, show them joined by " then " in #out.
JavaScript Event Loop exercisesconst order = [];
setTimeout(function () {
order.push("timer");
document.querySelector('#out').textContent = order.join(" then ");
}, 0);
order.push("sync");The timer waits for the code that is running to end, so sync is added first.
Write a Person class that stores a name. Build one with the name Ada and show its name in #out.
JavaScript Classes exercisesclass Person {
constructor(name) {
this.name = name;
}
}
document.querySelector('#out').textContent = new Person("Ada").name;new Person("Ada") runs the constructor, which stores Ada as name.
Write a class whose constructor stores a name and an age. Build one with Ada and 36, and show Ada is 36 in #out.
JavaScript Class Constructor exercisesclass Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const ada = new Person("Ada", 36);
document.querySelector('#out').textContent = ada.name + " is " + ada.age;The constructor stores both values, so the object can be read for either.
Write an Account class that starts with a balance and has a deposit method that adds to it and returns it. Start with 100, deposit 50 and show the result in #out.
JavaScript Class Methods exercisesclass Account {
constructor(balance) {
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
return this.balance;
}
}
document.querySelector('#out').textContent = String(new Account(100).deposit(50));deposit adds 50 to the balance of 100 and returns 150.
Write a Counter class with a count field that starts at 0 and an up method that adds one and returns it. Call up once and show the result in #out.
JavaScript Class Fields exercisesclass Counter {
count = 0;
up() {
this.count++;
return this.count;
}
}
document.querySelector('#out').textContent = String(new Counter().up());Each new Counter gets its own count of 0, and up makes it 1.
Write a class with a static double method. Call it on the class with 5 and show the result in #out.
JavaScript Static Members exercisesclass MathHelper {
static double(n) {
return n * 2;
}
}
document.querySelector('#out').textContent = String(MathHelper.double(5));A static method belongs to the class, so no object is needed.
Write an Animal class whose speak method returns some sound. Make Dog extend it, and show what a dog's speak returns in #out.
JavaScript Class Inheritance exercisesclass Animal {
speak() {
return "some sound";
}
}
class Dog extends Animal {}
document.querySelector('#out').textContent = new Dog().speak();Dog has no speak of its own, so it uses the one from Animal.
Animal stores a name. Make Dog extend it, pass the name up with super and store a breed. Build Rex the collie and show Rex the collie in #out.
JavaScript super Keyword exercisesclass Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
}
const rex = new Dog("Rex", "collie");
document.querySelector('#out').textContent = rex.name + " the " + rex.breed;super lets Animal store the name, and then Dog adds the breed.
Animal's speak returns some sound. Make Dog extend it with its own speak that returns woof, and show what a dog's speak returns in #out.
JavaScript Method Overriding exercisesclass Animal {
speak() {
return "some sound";
}
}
class Dog extends Animal {
speak() {
return "woof";
}
}
document.querySelector('#out').textContent = new Dog().speak();JavaScript looks in Dog before Animal, so it finds woof.
Write an Account class with a private balance of 100 and a getBalance method. Show the balance in #out.
JavaScript Private Fields exercisesclass Account {
#balance = 100;
getBalance() {
return this.#balance;
}
}
document.querySelector('#out').textContent = String(new Account().getBalance());#balance cannot be read from outside, so getBalance returns it.
Write a Rectangle class with a width, a height and an area getter. Show the area of a 4 by 5 rectangle in #out.
JavaScript Class Getters and Setters exercisesclass Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
}
document.querySelector('#out').textContent = String(new Rectangle(4, 5).area);Reading area runs the getter, which multiplies 4 by 5.
Write a Dog class and build one. Use instanceof to show whether it is a Dog, true or false, in #out.
JavaScript instanceof exercisesclass Dog {}
document.querySelector('#out').textContent = String(new Dog() instanceof Dog);The object was built from Dog, so instanceof gives true.
Write an Animal class and build one. Show whether its prototype is Animal.prototype, true or false, in #out.
JavaScript Prototype Chain exercisesclass Animal {}
const dog = new Animal();
document.querySelector('#out').textContent = String(Object.getPrototypeOf(dog) === Animal.prototype);An object built from a class has that class's prototype, so they are the same.
document.querySelector('#out').textContent = typeof "hello";Text in quotes is a string.
Given const text = "42", turn it into a number and add 8. Show the result in #out.
JavaScript Type Conversion exercisesconst text = "42";
document.querySelector('#out').textContent = String(Number(text) + 8);Number("42") is the number 42, so + adds 8.
Use + on the text "5" and the number 3. Show the result in #out.
JavaScript Type Coercion exercisesdocument.querySelector('#out').textContent = "5" + 3;One side is text, so 3 becomes text too and they are joined: 53.
Compare "5" and 5 with ==. Show loosely equal in #out when they match, otherwise not equal.
JavaScript == vs === exercisesdocument.querySelector('#out').textContent = "5" == 5 ? "loosely equal" : "not equal";== turns the text into a number first, so they match. === would not.
Show text is truthy in #out if "hello" is truthy, otherwise text is falsy.
JavaScript Truthy and Falsy exercisesdocument.querySelector('#out').textContent = "hello" ? "text is truthy" : "text is falsy";Text with any character in it is truthy, so the first value is used.
Declare a variable with let but give it no value. Show its value in #out.
JavaScript null and undefined exerciseslet notSet;
document.querySelector('#out').textContent = String(notSet);A variable with no value holds undefined.
document.querySelector('#out').textContent = String(Number("hello"));hello is not a number, so the conversion gives NaN.
Set a to 1 and copy it to b. Change b to 2 and show a in #out.
JavaScript Primitives and References exerciseslet a = 1;
let b = a;
b = 2;
document.querySelector('#out').textContent = String(a);Numbers are copied by value, so a is still 1.
Show how many characters "Ada Lovelace" has in #out.
JavaScript Strings exercisesconst name = "Ada Lovelace";
document.querySelector('#out').textContent = String(name.length);Three letters, a space and eight letters make 12.
Given const name = "Ada", use a template literal to show Hello Ada in #out.
JavaScript Template Literals exercisesconst name = "Ada";
document.querySelector('#out').textContent = `Hello ${name}`;The part in ${ } is replaced by the value of name.
Show She said "hello" in #out, with the quotes, from a string written in double quotes.
JavaScript String Escape Characters exercisesdocument.querySelector('#out').textContent = "She said \"hello\"";The backslash tells JavaScript that the quote is part of the text and does not end it.
Given const name = "Ada", show it in capitals in #out.
JavaScript String Case exercisesconst name = "Ada";
document.querySelector('#out').textContent = name.toUpperCase();toUpperCase returns a copy in capitals.
Show contains it in #out if "JavaScript Basics" includes Script, otherwise missing.
JavaScript String Search exercisesconst text = "JavaScript Basics";
document.querySelector('#out').textContent = text.includes("Script") ? "contains it" : "missing";Script is part of JavaScript, so includes gives true.
Take the first four characters of "JavaScript" with slice. Show them in #out.
JavaScript String slice exercisesconst text = "JavaScript";
document.querySelector('#out').textContent = text.slice(0, 4);slice(0, 4) takes positions 0, 1, 2 and 3: Java.
Change only the first cat in "cat cat cat" to dog. Show the result in #out.
JavaScript String replace exercisesconst text = "cat cat cat";
document.querySelector('#out').textContent = text.replace("cat", "dog");replace stops after one match, so the other two cats stay.
Split "a,b,c" at the commas. Show how many parts there are in #out.
JavaScript String split exercisesconst text = "a,b,c";
document.querySelector('#out').textContent = String(text.split(",").length);split gives ["a", "b", "c"], which has 3 items.
Remove the spaces round " Ada " with trim. Show the result in #out.
JavaScript String trim exercisesconst entered = " Ada ";
document.querySelector('#out').textContent = entered.trim();trim removes the spaces at both ends and leaves the middle alone.
Given const first = "Ada" and const last = "Lovelace", join them with a space. Show the result in #out.
JavaScript String Concatenation exercisesconst first = "Ada";
const last = "Lovelace";
document.querySelector('#out').textContent = first + " " + last;first + " " + last puts the space between the names.
Show apple first in #out if "apple" comes before "banana", otherwise banana first.
JavaScript String Comparison exercisesdocument.querySelector('#out').textContent = "apple" < "banana" ? "apple first" : "banana first";a comes before b, so "apple" < "banana" is true.
Set text to hello. Change it to capitals and store the result back in the same variable, then show it in #out.
JavaScript String Immutability exerciseslet text = "hello";
text = text.toUpperCase();
document.querySelector('#out').textContent = text;toUpperCase returns new text, so it has to be stored to be kept.
Store 10 and 3 in two variables. Show their sum in #out.
JavaScript Numbers exercisesconst a = 10;
const b = 3;
document.querySelector('#out').textContent = a + b;Both are numbers, so + adds them.
Show 19.567 with two decimals in #out. Use toFixed.
JavaScript Number Methods exercisesconst price = 19.567;
document.querySelector('#out').textContent = price.toFixed(2);19.567 rounds to 19.57 with two decimals.
Read the number in "250px" and show it in #out.
JavaScript parseInt and parseFloat exercisesconst width = "250px";
document.querySelector('#out').textContent = String(parseInt(width, 10));parseInt reads 250 and stops at p.
Show exact in #out if 0.1 + 0.2 equals 0.3, otherwise not exact.
JavaScript Number Precision exercisesdocument.querySelector('#out').textContent = 0.1 + 0.2 === 0.3 ? "exact" : "not exact";0.1 + 0.2 is stored as 0.30000000000000004, so it is not equal to 0.3.
Show the absolute value of -5 in #out. Use Math.abs.
JavaScript Math Object exercisesdocument.querySelector('#out').textContent = String(Math.abs(-5));-5 is five away from 0, so the result is 5.
Round 4.5 to the nearest whole number with Math.round. Show it in #out.
JavaScript Math Rounding exercisesdocument.querySelector('#out').textContent = String(Math.round(4.5));4.5 is halfway, and Math.round goes up, to 5.
Get a random number. Show in range in #out if it is 0 or more and less than 1, otherwise out of range.
JavaScript Math.random exercisesconst value = Math.random();
document.querySelector('#out').textContent = value >= 0 && value < 1 ? "in range" : "out of range";Math.random always gives a number from 0 up to, but not including, 1.
Show the largest of 5, 2 and 9 in #out. Use Math.max.
JavaScript Math.min and Math.max exercisesdocument.querySelector('#out').textContent = String(Math.max(5, 2, 9));9 is the largest of the three.
Show 1234567 with commas between the thousands in #out. Use toLocaleString with "en-GB".
JavaScript Number Formatting exercisesdocument.querySelector('#out').textContent = (1234567).toLocaleString("en-GB");British English puts a comma after every three digits.
Show an integer in #out if 42.5 is a whole number, otherwise not an integer.
JavaScript Integer Safety exercisesdocument.querySelector('#out').textContent = Number.isInteger(42.5) ? "an integer" : "not an integer";42.5 has a decimal part, so it is not an integer.
Read the length of null inside try. In catch, set a message to something went wrong and show it in #out.
JavaScript Errors exerciseslet message;
try {
const value = null;
value.length;
} catch (error) {
message = "something went wrong";
}
document.querySelector('#out').textContent = message;null has no length, so an error is thrown and catch runs.
Parse the text not json with JSON.parse inside try. In catch, show could not parse that in #out.
JavaScript try catch exerciseslet result;
try {
result = JSON.parse("not json");
} catch (error) {
result = "could not parse that";
}
document.querySelector('#out').textContent = result;The text is not valid JSON, so JSON.parse throws and catch runs.
Write a function that throws new Error("age cannot be negative") for an age below 0. Call it with -5, catch the error and show its message in #out.
JavaScript throw exercisesfunction setAge(age) {
if (age < 0) {
throw new Error("age cannot be negative");
}
return age;
}
let message;
try {
setAge(-5);
} catch (error) {
message = error.message;
}
document.querySelector('#out').textContent = message;-5 is below 0, so the function throws, and catch reads the message.
Add trying to an array in try and then cause an error. Add caught in catch and cleaned up in finally. Show them joined by spaces in #out.
JavaScript finally exercisesconst steps = [];
try {
steps.push("trying");
null.length;
} catch (error) {
steps.push("caught");
} finally {
steps.push("cleaned up");
}
document.querySelector('#out').textContent = steps.join(" ");try fails after its first line, catch runs, and finally always runs last.
Read the length of null and catch the error. Show the error's name in #out.
JavaScript Error Types exerciseslet name;
try {
null.length;
} catch (error) {
name = error.name;
}
document.querySelector('#out').textContent = name;Reading a property of null is a TypeError.
Write a ValidationError class that extends Error and sets its name to ValidationError. Throw one, catch it and show its name in #out.
JavaScript Custom Errors exercisesclass ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
let name;
try {
throw new ValidationError("name is required");
} catch (error) {
name = error.name;
}
document.querySelector('#out').textContent = name;The class is an Error with its own name, so catch can tell it apart.
Write a function that parses JSON text and returns null when that fails. Give it not json, and show nothing parsed in #out if the result is null, otherwise parsed.
JavaScript Error Handling Patterns exercisesfunction parseUser(text) {
try {
return JSON.parse(text);
} catch (error) {
return null;
}
}
document.querySelector('#out').textContent = parseUser("not json") === null ? "nothing parsed" : "parsed";The text is not JSON, so catch returns null and the check picks nothing parsed.
Given const a = "10" and const b = 10, show the typeof both in #out, with a space between.
JavaScript Debugging exercisesconst a = "10";
const b = 10;
document.querySelector('#out').textContent = typeof a + " " + typeof b;They look alike, but one is text and the other a number.
Make a Map and set Ada to 90. Read it back and show it in #out.
JavaScript Map exercisesconst scores = new Map();
scores.set("Ada", 90);
document.querySelector('#out').textContent = String(scores.get("Ada"));get("Ada") gives the value stored under Ada.
Make a Map where Ada is 90 and Grace is 95. Show its keys joined by commas in #out.
JavaScript Map Methods exercisesconst scores = new Map([["Ada", 90], ["Grace", 95]]);
document.querySelector('#out').textContent = [...scores.keys()].join(",");[...scores.keys()] is ["Ada", "Grace"].
const tags = new Set();
tags.add("js");
tags.add("css");
tags.add("js");
document.querySelector('#out').textContent = String(tags.size);js was already there, so adding it again changes nothing.
Combine new Set([1, 2, 3]) and new Set([2, 3, 4]) into one set. Show its values joined by commas in #out.
JavaScript Set Operations exercisesconst a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
document.querySelector('#out').textContent = [...new Set([...a, ...b])].join(",");The array has 2 and 3 twice, and the new Set keeps each once.
Use an object as a key in a WeakMap and store cached. Read it back and show it in #out.
JavaScript WeakMap and WeakSet exercisesconst cache = new WeakMap();
const user = { name: "Ada" };
cache.set(user, "cached");
document.querySelector('#out').textContent = cache.get(user);The same object finds the value again.
Build the date January 15 2026 and show its year in #out.
JavaScript Dates exercisesconst date = new Date(Date.UTC(2026, 0, 15));
document.querySelector('#out').textContent = String(date.getUTCFullYear());Date.UTC(2026, 0, 15) is January 15, and its year is 2026.
Show January 15 2026 as 15/01/2026 in #out. Build it with Date.UTC and format it with toLocaleDateString, "en-GB" and the time zone UTC.
JavaScript Date Formatting exercisesconst date = new Date(Date.UTC(2026, 0, 15));
document.querySelector('#out').textContent = date.toLocaleDateString("en-GB", { timeZone: "UTC" });The British order is day, month, year.
Show how many days there are from January 1 2026 to January 15 2026 in #out. Subtract the dates.
JavaScript Date Arithmetic exercisesconst start = new Date(Date.UTC(2026, 0, 1));
const end = new Date(Date.UTC(2026, 0, 15));
document.querySelector('#out').textContent = String(Math.round((end - start) / 86400000));The difference in milliseconds divided by one day gives 14.
Build January 15 2026 at 14:30 UTC. Show its UTC hours in #out.
JavaScript Date Components exercisesconst date = new Date(Date.UTC(2026, 0, 15, 14, 30));
document.querySelector('#out').textContent = String(date.getUTCHours());The time is 14:30, so the hours are 14.
Show the typeof the current timestamp in #out. Use Date.now.
JavaScript Timestamps exercisesdocument.querySelector('#out').textContent = typeof Date.now();A timestamp is a plain number.
Build January 32 2026 with Date.UTC. Show the month number it lands on in #out.
JavaScript Date Pitfalls exercisesconst date = new Date(Date.UTC(2026, 0, 32));
document.querySelector('#out').textContent = String(date.getUTCMonth());January has 31 days, so day 32 is February 1, and February is month 1.
Use a regular expression to show found in #out if "a cat sat" contains cat, otherwise missing.
JavaScript Regular Expressions exercisesdocument.querySelector('#out').textContent = /cat/.test("a cat sat") ? "found" : "missing";The text contains cat, so test gives true.
Use a regular expression to show has a digit in #out if "abc1" contains a digit, otherwise no digits.
JavaScript Regex Characters exercisesdocument.querySelector('#out').textContent = /\d/.test("abc1") ? "has a digit" : "no digits";1 is a digit, so the pattern matches.
Use a regular expression to get the whole number out of "room 42". Show it in #out.
JavaScript Regex Quantifiers exercisesdocument.querySelector('#out').textContent = "room 42".match(/\d+/)[0];\d+ takes both digits. \d alone would stop at 4.
Use a regular expression to show accepted in #out if "abc2026xyz" is exactly four digits, otherwise rejected.
JavaScript Regex Anchors exercisesdocument.querySelector('#out').textContent = /^\d{4}$/.test("abc2026xyz") ? "accepted" : "rejected";There are letters round the digits, so the anchored pattern does not match.
Use a regular expression with a group to get the year out of "2026-01-15". Show it in #out.
JavaScript Regex Groups exercisesdocument.querySelector('#out').textContent = "2026-01-15".match(/(\d{4})-(\d{2})-(\d{2})/)[1];The first group holds the four digits before the dash.
Use search to show the position of the first digit in "abc 1" in #out.
JavaScript Regex Methods exercisesdocument.querySelector('#out').textContent = String("abc 1".search(/\d/));a, b, c and the space are positions 0 to 3, so the digit is at 4.
Use a regular expression to show accepted in #out if "12345" is nothing but digits, otherwise rejected.
JavaScript Regex Validation exercisesdocument.querySelector('#out').textContent = /^\d+$/.test("12345") ? "accepted" : "rejected";Every character is a digit, so the pattern matches the whole text.
Use replace and a regular expression to turn every run of spaces and tabs in "a b\t\tc" into one space. Show the result in #out.
JavaScript Regex in Practice exercisesdocument.querySelector('#out').textContent = "a b\t\tc".replace(/\s+/g, " ");Each run, however long, is replaced by one space.
Save Ada under the key name in localStorage. Read it back and show it in #out.
JavaScript localStorage exerciseslocalStorage.setItem("name", "Ada");
document.querySelector('#out').textContent = localStorage.getItem("name");getItem("name") gives the saved text.
Save 2 under the key step in sessionStorage. Read it back and show it in #out.
JavaScript sessionStorage exercisessessionStorage.setItem("step", "2");
document.querySelector('#out').textContent = sessionStorage.getItem("step");The value stays until the tab is closed.
Save { name: "Ada", age: 36 } in localStorage as JSON. Read it back and show the name in #out.
JavaScript Storing Objects exercisesconst user = { name: "Ada", age: 36 };
localStorage.setItem("user", JSON.stringify(user));
const saved = JSON.parse(localStorage.getItem("user"));
document.querySelector('#out').textContent = saved.name;stringify turns the object into text, and parse turns it back.
Listen for the storage event on window, then save something in localStorage. Show fired in #out if the event ran, otherwise not fired.
JavaScript Storage Events exerciseslet heard = false;
window.addEventListener("storage", function () {
heard = true;
});
localStorage.setItem("test", "value");
document.querySelector('#out').textContent = heard ? "fired" : "not fired";The storage event only runs in other tabs, so here it does not fire.
document.querySelector('#out').textContent = typeof window;window is an object that holds everything in the page.
Parse "https://example.com/products?id=42" with new URL. Show its host in #out.
JavaScript location Object exercisesconst url = new URL("https://example.com/products?id=42");
document.querySelector('#out').textContent = url.hostname;URL splits the address, and its hostname is example.com.
Show the typeof history.pushState in #out.
JavaScript history Object exercisesdocument.querySelector('#out').textContent = typeof history.pushState;pushState is a method, so its type is function.
Show the typeof navigator.onLine in #out.
JavaScript navigator Object exercisesdocument.querySelector('#out').textContent = typeof navigator.onLine;onLine is true or false, which is the type boolean.
Write a function that is called at once and returns an object with a double method. Keep the number 2 in a variable inside it and use it in double. Show double(5) in #out.
JavaScript Modules exercisesconst mathModule = (function () {
const secret = 2;
return {
double: function (n) { return n * secret; }
};
})();
document.querySelector('#out').textContent = String(mathModule.double(5));Only double can reach the private number, and 5 * 2 is 10.
Make an object named moduleExports with a double function and PI_ROUNDED set to 3. Show double(5) and PI_ROUNDED joined by " and " in #out.
JavaScript export exercisesconst moduleExports = {
double: function (n) { return n * 2; },
PI_ROUNDED: 3
};
document.querySelector('#out').textContent = moduleExports.double(5) + " and " + moduleExports.PI_ROUNDED;The object stands in for a module: each property is one export.
Make an object named mathModule with a double function. Take double out by destructuring and show double(5) in #out.
JavaScript import exercisesconst mathModule = { double: function (n) { return n * 2; } };
const { double } = mathModule;
document.querySelector('#out').textContent = String(double(5));The braces pick out one export by name, as import does.
Write a function that returns found it if #out is on the page, otherwise not ready yet. Call it and show the result in #out.
JavaScript Module Scripts exercisesfunction readAfterParsed() {
return document.querySelector('#out') ? "found it" : "not ready yet";
}
document.querySelector('#out').textContent = readAfterParsed();The script runs after #out, so it is found. A module script waits for the page in the same way.
Write a function that returns a promise for an object with a double function. Use then or await to show double(5) in #out.
JavaScript Dynamic Import exercisesfunction importMathModule() {
return Promise.resolve({ double: function (n) { return n * 2; } });
}
importMathModule().then(function (module) {
document.querySelector('#out').textContent = String(module.double(5));
});import() gives a promise in the same way, so its exports are used in then.
Write a function that is called at once, keeps a count and returns an object with an increment method. Call increment twice and show the results joined by " and " in #out.
JavaScript Module Patterns exercisesconst counterModule = (function () {
let count = 0;
return {
increment: function () { count++; return count; }
};
})();
document.querySelector('#out').textContent = counterModule.increment() + " and " + counterModule.increment();The count lives on between calls, so the results are 1 and 2.
Get the iterator of [1, 2, 3] and show the first value it gives in #out.
JavaScript Iterators exercisesconst numbers = [1, 2, 3];
const iterator = numbers[Symbol.iterator]();
document.querySelector('#out').textContent = String(iterator.next().value);The first call to next gives the first value, 1.
Show the typeof an array's Symbol.iterator method in #out.
JavaScript Iterables exercisesdocument.querySelector('#out').textContent = typeof [][Symbol.iterator];An array has this method, which is what lets for...of work on it.
Write a generator function that yields 1, 2 and 3. Show the values joined by commas in #out.
JavaScript Generator Functions exercisesfunction* countTo(max) {
for (let i = 1; i <= max; i++) {
yield i;
}
}
document.querySelector('#out').textContent = [...countTo(3)].join(",");Each yield gives one value, and spread collects all three.
Write a generator that waits for a name at a yield, then yields Hello and that name. Send Ada in with next and show the result in #out.
JavaScript Generator Communication exercisesfunction* greeter() {
const name = yield;
yield "Hello " + name;
}
const g = greeter();
g.next();
document.querySelector('#out').textContent = g.next("Ada").value;next("Ada") gives Ada to the waiting yield, so the generator can greet it.
Make an object { from: 1, to: 3 } that can be spread, with a Symbol.iterator generator. Show its values joined by commas in #out.
JavaScript Custom Iterables exercisesconst range = {
from: 1,
to: 3,
[Symbol.iterator]: function* () {
for (let i = this.from; i <= this.to; i++) {
yield i;
}
}
};
document.querySelector('#out').textContent = [...range].join(",");Spread asks the object for its iterator, and the generator gives 1, 2 and 3.
Write a generator that never ends and yields 1, 2, 3 and so on. Take the first five values and show them joined by commas in #out.
JavaScript Lazy Sequences exercisesfunction* naturalNumbers() {
let n = 1;
while (true) { yield n; n++; }
}
function take(iterable, count) {
const result = [];
const it = iterable[Symbol.iterator]();
for (let i = 0; i < count; i++) { result.push(it.next().value); }
return result;
}
document.querySelector('#out').textContent = take(naturalNumbers(), 5).join(",");The generator only makes a value when asked, so it can be endless.
Write an async generator that yields 1, 2 and 3. Collect the values with for await and show them joined by commas in #out.
JavaScript Async Iteration exercisesasync function* countSlowly(max) {
for (let i = 1; i <= max; i++) {
await Promise.resolve();
yield i;
}
}
async function run() {
const values = [];
for await (const n of countSlowly(3)) {
values.push(n);
}
return values.join(",");
}
run().then(function (result) {
document.querySelector('#out').textContent = result;
});for await waits for each value before it goes on.
Measure how long a loop of 10000 turns takes. Show whether the time is 0 or more, true or false, in #out.
JavaScript Performance Basics exercisesconst started = Date.now();
let total = 0;
for (let i = 0; i < 10000; i++) { total += i; }
const elapsed = Date.now() - started;
document.querySelector('#out').textContent = String(elapsed >= 0);The end can never be before the start, so the time is 0 or more.
Write debounce(fn, delay), which runs fn only after calls stop for that delay. Call a debounced counter three times and show the count straight away in #out.
JavaScript Debounce exercisesfunction debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(function () { fn(...args); }, delay);
};
}
let calls = 0;
const debounced = debounce(function () { calls++; }, 10);
debounced();
debounced();
debounced();
document.querySelector('#out').textContent = String(calls);The delay has not passed yet, so the function has run 0 times.
Write throttle(fn, interval), which runs fn at once and then ignores calls until the interval has passed. Call a throttled counter three times and show the count in #out.
JavaScript Throttle exercisesfunction throttle(fn, interval) {
let ready = true;
return function (...args) {
if (!ready) return;
ready = false;
fn(...args);
setTimeout(function () { ready = true; }, interval);
};
}
let calls = 0;
const throttled = throttle(function () { calls++; }, 10);
throttled();
throttled();
throttled();
document.querySelector('#out').textContent = String(calls);Only the first call is allowed, so the count is 1.
Write memoize(fn), which remembers results. Memoize a doubling function that counts its runs, call it three times with 5 and show the count in #out.
JavaScript Memoization exercisesfunction memoize(fn) {
const cache = new Map();
return function (n) {
if (cache.has(n)) return cache.get(n);
const result = fn(n);
cache.set(n, result);
return result;
};
}
let calls = 0;
const double = memoize(function (n) { calls++; return n * 2; });
double(5);
double(5);
double(5);
document.querySelector('#out').textContent = String(calls);The first call saves the result and the next two reuse it, so it runs once.
Write timeIt(fn), which runs fn and returns how long it took. Show whether the time is 0 or more, true or false, in #out.
JavaScript Performance Measurement exercisesfunction timeIt(fn) {
const start = performance.now();
fn();
return performance.now() - start;
}
const duration = timeIt(function () {
let total = 0;
for (let i = 0; i < 1000; i++) { total += i; }
});
document.querySelector('#out').textContent = String(duration >= 0);The end can never be before the start, so the result is true.
Make a Proxy round { name: "Ada" } whose get handler returns the property. Show the name read through the proxy in #out.
JavaScript Proxy exercisesconst target = { name: "Ada" };
const proxy = new Proxy(target, {
get(obj, key) { return obj[key]; }
});
document.querySelector('#out').textContent = proxy.name;Reading proxy.name calls get, which passes the read through.
Read the name of { name: "Ada" } with Reflect.get. Show it in #out.
JavaScript Reflect exercisesconst person = { name: "Ada" };
document.querySelector('#out').textContent = Reflect.get(person, "name");Reflect.get does the same as a dot, as a function.
The first in every lesson is free. The rest come with the practice plan, and your first month costs nothing.
See the practice planRead the lesson in the JavaScript tutorial, then come back and solve it.
JavaScript tutorial