Skip to main content

JavaScript Exercises

HTML5andCSS3 logo

0 of 207 solved

Use JavaScript to put the word running into #out.

Acceptance criteria

  1. 1.#out should show running.
  2. 2.Put the text on the page with JavaScript.

1
0 × 0

Your page appears here. Press Run to see it, or Submit to check your answer.

JavaScript exercises with solutions

Pick a result and write the JavaScript that makes it. Every exercise here runs without an account.

Exercises
207
Topics
24
Solved by you
0

207 shown

JavaScript Introduction

  1. 1. Make the page say something

    Use JavaScript to put the word running into #out.

    Exercises: What is JavaScript
    Show solution
    document.querySelector('#out').textContent = "running";

    querySelector finds the element with the id out, and textContent replaces the text inside it.

  2. 2. Show dynamic typing

    Give one variable the number 10, then the text "ten". Show its final type in #out.

    JavaScript Features exercises
    Show solution
    let 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.

  3. 3. Write a complete statement

    Store the word complete in a variable. Show the variable in #out.

    JavaScript Syntax exercises
    Show solution
    const state = "complete";
    document.querySelector('#out').textContent = state;

    const creates the variable, and the second statement reads it to fill the page.

  4. 4. Find an element and change it

    Find the element with the id out and set its text to connected.

    Exercises: How to Add JavaScript
    Show solution
    document.querySelector("#out").textContent = "connected";

    The script can find #out because the element already exists when the script runs.

  5. 5. Write plain text

    Put the word plain into #out using textContent.

    JavaScript Output exercises
    Show solution
    document.querySelector('#out').textContent = "plain";

    textContent writes the value as text, so tags in it would show as characters.

  6. 6. Add a line comment

    Write a // comment that says what your code does. Then show the word documented in #out.

    JavaScript Comments exercises
    Show solution
    // Show the current state
    document.querySelector('#out').textContent = "documented";

    The browser skips everything after // on that line. Only the next line runs.

JavaScript Basics

  1. 7. Declare a variable with let

    Declare a variable named score with let and set it to 42. Show it in #out.

    JavaScript Variables exercises
    Show solution
    let score = 42;
    document.querySelector('#out').textContent = score;

    let score = 42 creates the variable, and reading score gives 42.

  2. 8. Report a number's type

    Use typeof to show the type of the value 7 in #out.

    JavaScript Data Types exercises
    Show solution
    document.querySelector('#out').textContent = typeof 7;

    Every number in JavaScript, whole or decimal, has the type number.

  3. 9. Add two numbers

    Add 12 and 8. Show the sum in #out.

    JavaScript Operators exercises
    Show solution
    document.querySelector('#out').textContent = 12 + 8;

    Without quotes 12 and 8 are numbers, so + adds them. With quotes it would join them into 128.

JavaScript Statement & Expression

  1. 10. Run statements in order

    Set a variable to first, then change it to second. Show its final value in #out.

    JavaScript Statements exercises
    Show solution
    let label = "first";
    label = "second";
    document.querySelector('#out').textContent = label;

    Statements run from top to bottom, so the last value set is the one shown.

  2. 11. Check an expression

    If 3 * 7 equals 21, show correct in #out. Otherwise show wrong.

    JavaScript Expressions exercises
    Show solution
    document.querySelector('#out').textContent = (3 * 7 === 21) ? "correct" : "wrong";

    3 * 7 works out to 21, the comparison gives true, and true picks correct.

  3. 12. Use the const keyword

    Declare a constant holding the word fixed. Show it in #out.

    JavaScript Keywords exercises
    Show solution
    const value = "fixed";
    document.querySelector('#out').textContent = value;

    const is a keyword: a word JavaScript keeps for itself, here to create a constant.

  4. 13. Name a variable clearly

    Store the word named in a variable called userStatus. Show it in #out.

    JavaScript Identifiers exercises
    Show solution
    const userStatus = "named";
    document.querySelector('#out').textContent = userStatus;

    userStatus says what the value is for, which a name like x would not.

  5. 14. Match variable casing

    Store the word matched in a variable called userName. Show it in #out.

    JavaScript Case Sensitivity exercises
    Show solution
    const userName = "matched";
    document.querySelector('#out').textContent = userName;

    JavaScript compares every letter, so only userName with a capital N finds the variable.

  6. 15. End statements with semicolons

    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 exercises
    Show solution
    const a = "first";
    document.querySelector('#out').textContent = "terminated";

    A semicolon marks where one statement stops and the next one starts.

  7. 16. Group statements in a block

    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 exercises
    Show solution
    const 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.

JavaScript Conditions

  1. 17. Show a message when true

    Set age to 20. If age is 18 or more, show adult in #out.

    JavaScript if Statement exercises
    Show solution
    const 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.

  2. 18. Grade a score

    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 exercises
    Show solution
    const score = 87;
    const result = document.getElementById('result');
    
    if (score >= 90) {
      result.textContent = 'A';
    } else if (score >= 80) {
      result.textContent = 'B';
    } else {
      result.textContent = 'C';
    }
  3. 19. Grade a score

    Set score to 85. Show A in #out for 90 or more, B for 80 or more, otherwise C.

    JavaScript else if Statement exercises
    Show solution
    const 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.

  4. 20. Switch on a day

    Set day to "Monday". Use a switch to show start in #out for Monday and other for any other day.

    JavaScript switch Statement exercises
    Show solution
    const 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.

  5. 21. Choose between two values

    Set age to 20. Use ? : to show adult in #out when age is 18 or more, otherwise minor.

    JavaScript Ternary Operator exercises
    Show solution
    const age = 20;
    document.querySelector('#out').textContent = age >= 18 ? "adult" : "minor";

    20 >= 18 is true, so the value before the colon is used.

JavaScript Loops

  1. 22. Render a numbered list with a loop

    Use a for loop to append 5 <li> elements to #list, with text "Item 1" through "Item 5".

    JavaScript for Loop exercises
    Show solution
    const list = document.getElementById('list');
    
    for (let i = 1; i <= 5; i++) {
      const item = document.createElement('li');
      item.textContent = 'Item ' + i;
      list.appendChild(item);
    }
  2. 23. Count to four

    Use a while loop to count 1, 2, 3, 4. Show them joined by commas in #out.

    JavaScript while Loop exercises
    Show solution
    const 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.

  3. 24. Run at least once

    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 exercises
    Show solution
    let 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.

  4. 25. Stop at a match

    Loop from 1 to 10 and stop at the first number that divides by 4. Show that number in #out.

    JavaScript break Statement exercises
    Show solution
    let 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.

  5. 26. Skip one number

    Add the numbers 1 to 6 but skip 4 with continue. Show the total in #out.

    JavaScript continue Statement exercises
    Show solution
    let 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.

  6. 27. List the property names

    Loop over { name: "John", age: 30, city: "London" } with for...in. Show the property names joined by dashes in #out.

    JavaScript for in Loop exercises
    Show solution
    const 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.

  7. 28. Add up an array

    Add every number in [10, 20, 30, 40] with for...of. Show the total in #out.

    JavaScript for of Loop exercises
    Show solution
    const 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.

  8. 29. Count the turns

    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 exercises
    Show solution
    let 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.

JavaScript Functions

  1. 30. Write your first function

    Write a function that returns the word Hello. Call it and show the result in #out.

    JavaScript Functions exercises
    Show solution
    function greet() {
      return "Hello";
    }
    document.querySelector('#out').textContent = greet();

    The function runs when it is called, and the call is replaced by what it returns.

  2. 31. Declare a function

    Declare a function named square that returns a number times itself. Show the square of 9 in #out.

    JavaScript Function Declarations exercises
    Show solution
    function square(n) {
      return n * n;
    }
    document.querySelector('#out').textContent = square(9);

    n is 9 inside the function, so it returns 9 * 9.

  3. 32. Store a function in a variable

    Store a function that doubles a number in a variable. Show the result for 16 in #out.

    JavaScript Function Expressions exercises
    Show solution
    const 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.

  4. 33. Use two parameters

    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 exercises
    Show solution
    function 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.

  5. 34. Add a default

    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 exercises
    Show solution
    function greet(name = "friend") {
      return "Hello " + name;
    }
    document.querySelector('#out').textContent = greet();

    No value was passed, so the parameter takes its default, friend.

  6. 35. Add up any number of values

    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 exercises
    Show solution
    function 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.

  7. 36. Return a value

    Write a function that returns the sum of two numbers. Show the result for 3 and 4 in #out.

    JavaScript return Statement exercises
    Show solution
    function 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.

  8. 37. Write an arrow function

    Write an arrow function that doubles a number. Show the result for 25 in #out.

    JavaScript Arrow Functions exercises
    Show solution
    const double = (n) => {
      return n * 2;
    };
    document.querySelector('#out').textContent = double(25);

    n is 25, so n * 2 gives 50.

  9. 38. Pass a callback

    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 exercises
    Show solution
    function 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.

  10. 39. Transform with map

    Use map to add 20 percent to each price in [100, 200]. Show the results joined by commas in #out.

    JavaScript Higher Order Functions exercises
    Show solution
    document.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.

  11. 40. Count down with recursion

    Write a function that calls itself to count down from 3 to 1. Show the numbers joined by dashes in #out.

    JavaScript Recursion exercises
    Show solution
    function 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.

  12. 41. Write an IIFE

    Write a function that is called at once and returns 6 times 7. Store the answer and show it in #out.

    JavaScript IIFE exercises
    Show solution
    const answer = (function () {
      return 6 * 7;
    })();
    document.querySelector('#out').textContent = answer;

    The last brackets call the function straight away, so answer holds 42.

  13. 42. Use call

    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 exercises
    Show solution
    const 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.

  14. 43. Write a pure function

    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 exercises
    Show solution
    function 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.

JavaScript Scope & Hoisting

  1. 44. Read a global variable

    Store My Site in a variable outside any function. Write a function that returns it, and show the result in #out.

    JavaScript Scope exercises
    Show solution
    const 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.

  2. 45. Declare inside a block

    Declare a let variable inside braces. Outside the braces, show its typeof in #out.

    JavaScript Block Scope exercises
    Show solution
    {
      let message = "inside";
    }
    document.querySelector('#out').textContent = typeof message;

    let only exists inside its block. Outside, the name is unknown and typeof gives undefined.

  3. 46. A var read too early

    Show the typeof of a var variable before the line that gives it the value 5. #out should show undefined.

    JavaScript Hoisting exercises
    Show solution
    document.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.

  4. 47. Read after declaring

    Declare a let variable holding ready. Read it on the next line and show it in #out.

    JavaScript Temporal Dead Zone exercises
    Show solution
    let state = "ready";
    document.querySelector('#out').textContent = state;

    A let variable cannot be used before its line. After that line it works normally.

  5. 48. Build a counter

    Write a function that returns a counting function. Call the counter three times and show the results joined by commas in #out.

    JavaScript Closures exercises
    Show solution
    function 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.

  6. 49. Use this in a method

    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 exercises
    Show solution
    const 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.

JavaScript Arrays

  1. 50. Create an array

    Create an array holding "Apple", "Banana" and "Mango". Show how many items it has in #out.

    JavaScript Arrays exercises
    Show solution
    const fruits = ["Apple", "Banana", "Mango"];
    document.querySelector('#out').textContent = fruits.length;

    length is the number of items, so an array of three fruits gives 3.

  2. 51. Read the first item

    Create the array ["Apple", "Banana", "Mango"]. Show its first item in #out.

    JavaScript Array Access exercises
    Show solution
    const fruits = ["Apple", "Banana", "Mango"];
    document.querySelector('#out').textContent = fruits[0];

    The first item is at position 0, so fruits[0] is Apple.

  3. 52. Add to the end

    Start with the array ["Ada"]. Push "Grace" and "Alan" onto it. Show the result joined by commas in #out.

    JavaScript Array push and pop exercises
    Show solution
    const 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.

  4. 53. Take a slice

    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 exercises
    Show solution
    const 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.

  5. 54. Join two arrays

    Combine [1, 2] and [3, 4] with concat. Show the result joined by commas in #out.

    JavaScript Array concat and join exercises
    Show solution
    const 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.

  6. 55. Find a position

    Find the position of "Banana" in ["Apple", "Banana", "Mango"]. Show it in #out.

    JavaScript Array Search exercises
    Show solution
    const 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.

  7. 56. Build text with forEach

    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 exercises
    Show solution
    const 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.

  8. 57. Double every number

    Use map to double each number in [1, 2, 3]. Show the result joined by commas in #out.

    JavaScript Array map exercises
    Show solution
    const 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.

  9. 58. Keep the even numbers

    Use filter to keep the even numbers in [1, 2, 3, 4, 5, 6]. Show them joined by commas in #out.

    JavaScript Array filter exercises
    Show solution
    const 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.

  10. 59. Add up a list with reduce

    Use reduce to add up [10, 20, 30]. Show the total in #out.

    JavaScript Array reduce exercises
    Show solution
    const 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.

  11. 60. Find the first match

    Use find to get the first number above 4 in [1, 8, 3, 12]. Show it in #out.

    JavaScript Array find exercises
    Show solution
    const 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.

  12. 61. Check for any match

    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 exercises
    Show solution
    const 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.

  13. 62. Sort numbers ascending

    Sort [10, 1, 5] from smallest to largest. Show the result joined by commas in #out.

    JavaScript Array sort exercises
    Show solution
    const 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.

  14. 63. Flatten one level

    Flatten [1, [2, 3], [4]] with flat. Show the result joined by commas in #out.

    JavaScript Array flat exercises
    Show solution
    const 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.

JavaScript Objects

  1. 64. Create an object

    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 exercises
    Show solution
    const person = { name: "Ada", age: 36 };
    document.querySelector('#out').textContent = person.name;

    person.name looks up the value stored under name.

  2. 65. Write a method

    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 exercises
    Show solution
    const 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.

  3. 66. List the keys

    Show the property names of { name: "Ada", age: 36 } joined by commas in #out. Use Object.keys.

    JavaScript Object keys and values exercises
    Show solution
    const person = { name: "Ada", age: 36 };
    document.querySelector('#out').textContent = Object.keys(person).join(",");

    Object.keys gives ["name", "age"], and join turns it into text.

  4. 67. Destructure an object

    Take name and age out of { name: "Ada", age: 36 } with destructuring. Show Ada is 36 in #out.

    JavaScript Destructuring exercises
    Show solution
    const 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.

  5. 68. Copy an object

    Copy { name: "Ada" } with spread and change the copy's name to Grace. Show the original's name in #out.

    JavaScript Object Spread exercises
    Show solution
    const 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.

  6. 69. Read a missing nested property

    Given const user = { name: "Ada" }, read user.address.city with optional chaining. Show the typeof of the result in #out.

    JavaScript Optional Chaining exercises
    Show solution
    const user = { name: "Ada" };
    document.querySelector('#out').textContent = typeof user.address?.city;

    address is missing, so ?. gives undefined instead of an error.

  7. 70. Keep a zero

    Given const settings = { volume: 0 }, use ?? to show the volume in #out, or 50 if there is none.

    JavaScript Nullish Coalescing exercises
    Show solution
    const settings = { volume: 0 };
    document.querySelector('#out').textContent = settings.volume ?? 50;

    0 is a real value, so ?? keeps it. || would have replaced it with 50.

  8. 71. Write a getter

    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 exercises
    Show solution
    const 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.

  9. 72. Turn an object into text

    Turn { name: "Ada" } into JSON text and show it in #out.

    JavaScript JSON exercises
    Show solution
    const person = { name: "Ada" };
    document.querySelector('#out').textContent = JSON.stringify(person);

    JSON.stringify writes the object as text with double quotes round names and values.

  10. 73. Freeze an object

    Freeze { theme: "dark" }, then try to change theme to "light". Show theme in #out.

    JavaScript Object freeze exercises
    Show solution
    const settings = Object.freeze({ theme: "dark" });
    settings.theme = "light";
    document.querySelector('#out').textContent = settings.theme;

    A frozen object ignores changes, so theme is still dark.

  11. 74. Write a constructor

    Write a Person constructor function that stores a name. Build one with the name Ada and show its name in #out.

    JavaScript Object Constructors exercises
    Show solution
    function 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.

JavaScript DOM

  1. 75. Read text from the page

    Read the text of the heading with the id title and show it in #out.

    JavaScript DOM exercises
    Show solution
    document.querySelector('#out').textContent = document.getElementById("title").textContent;

    Reading textContent gives Welcome, and setting #out's textContent shows it.

  2. 76. Select by class

    Read the text of the element with the class note and show it in #out.

    JavaScript DOM Selectors exercises
    Show solution
    document.querySelector('#out').textContent = document.querySelector(".note").textContent;

    querySelector(".note") finds the first element with that class.

  3. 77. Set plain text

    Set the text of #box to Hello. Then read it back and show it in #out.

    JavaScript DOM Content exercises
    Show solution
    const 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.

  4. 78. Read an attribute

    Use getAttribute to read the href of #link and show it in #out.

    JavaScript DOM Attributes exercises
    Show solution
    document.querySelector('#out').textContent = document.getElementById("link").getAttribute("href");

    getAttribute gives the value as written in the HTML, /about.

  5. 79. Set a colour

    Set the colour of #demo to red with style. Then read it back and show it in #out.

    JavaScript DOM Styles exercises
    Show solution
    const 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.

  6. 80. Add a class

    Add the class active to #demo. Show its full class list in #out.

    JavaScript classList exercises
    Show solution
    const 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.

  7. 81. Create an element

    Create a paragraph and put it in #box. Show how many paragraphs the box holds in #out.

    JavaScript Creating Elements exercises
    Show solution
    const 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.

  8. 82. Add an item to the end

    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 exercises
    Show solution
    const 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.

  9. 83. Remove an element

    Remove #demo from the page. Show how many paragraphs are left in #box in #out.

    JavaScript Removing Elements exercises
    Show solution
    document.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.

  10. 84. Find the parent

    Show the id of the element that holds #demo in #out.

    JavaScript DOM Traversal exercises
    Show solution
    document.querySelector('#out').textContent = document.getElementById("demo").parentElement.id;

    parentElement goes one step up, to the box.

  11. 85. Count the matches

    Show how many paragraphs are on the page in #out. Do not count #out itself.

    JavaScript DOM Collections exercises
    Show solution
    document.querySelector('#out').textContent = document.querySelectorAll("p:not(#out)").length;

    The page has three paragraphs besides #out, and length counts them.

  12. 86. Read an input value

    Show the value of the field with the id name in #out.

    JavaScript Forms and Inputs exercises
    Show solution
    document.querySelector('#out').textContent = document.getElementById("name").value;

    value holds what is in the field, which is Ada.

JavaScript Events

  1. 87. Handle a click

    When #btn is clicked, show Clicked in #out.

    JavaScript Events exercises
    Show solution
    document.getElementById("btn").addEventListener("click", function () {
      document.querySelector('#out').textContent = "Clicked";
    });

    The function is kept and runs each time the button is clicked.

  2. 88. Run a listener once

    Count clicks on #btn in #out, but use the once option so only the first click counts.

    JavaScript addEventListener exercises
    Show solution
    let 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.

  3. 89. Read the event type

    When #btn is clicked, show the type of the event in #out.

    JavaScript Event Object exercises
    Show solution
    document.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.

  4. 90. Handle mousedown

    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 exercises
    Show solution
    const 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.

  5. 91. Report the key pressed

    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 exercises
    Show solution
    const 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.

  6. 92. Handle a submit

    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 exercises
    Show solution
    const 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.

  7. 93. See a click bubble

    Listen for clicks on #box and show box heard it in #out. A click on the button inside should reach it.

    JavaScript Event Bubbling exercises
    Show solution
    document.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.

  8. 94. Delegate to a list

    Put one click listener on #list. Show the text of the item that was clicked in #out.

    JavaScript Event Delegation exercises
    Show solution
    document.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.

  9. 95. Stop a link navigating

    When #link is clicked, stop it from opening and show stayed here in #out.

    JavaScript preventDefault exercises
    Show solution
    document.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.

  10. 96. Remove a listener

    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 exercises
    Show solution
    const 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.

  11. 97. Wait for the page

    Show Ready in #out from inside a DOMContentLoaded listener.

    JavaScript Page Load Events exercises
    Show solution
    document.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.

  12. 98. Fire a custom event

    Listen for an event called itemAdded on #cart and show heard it in #out. Then fire that event.

    JavaScript Custom Events exercises
    Show solution
    const 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.

JavaScript Asynchronous

  1. 99. Report the running order

    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 exercises
    Show solution
    const 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.

  2. 100. Run something later

    Use setTimeout to show done in #out after 10 milliseconds.

    JavaScript setTimeout exercises
    Show solution
    setTimeout(function () {
      document.querySelector('#out').textContent = "done";
    }, 10);

    setTimeout keeps the function and runs it when the delay is over.

  3. 101. Tick three times

    Use setInterval to count to 3, then stop it and show the count in #out.

    JavaScript setInterval exercises
    Show solution
    let 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.

  4. 102. Pass a callback in

    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 exercises
    Show solution
    function 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.

  5. 103. Create a promise

    Make a promise that resolves with the name Ada after 5 milliseconds. Use then to show got Ada in #out.

    JavaScript Promises exercises
    Show solution
    const 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.

  6. 104. Chain two steps

    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 exercises
    Show solution
    Promise.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.

  7. 105. Catch a rejection

    Make a promise that rejects with new Error("no network"). Catch it and show caught: no network in #out.

    JavaScript Promise Errors exercises
    Show solution
    Promise.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.

  8. 106. Await a promise

    In an async function, await a promise that resolves with Ada. Show got Ada in #out.

    JavaScript async and await exercises
    Show solution
    async 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.

  9. 107. Catch a rejected await

    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 exercises
    Show solution
    async 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.

  10. 108. Wait for two promises

    Use Promise.all on promises that resolve with 1 and 2. Show both values joined by a comma in #out.

    JavaScript Promise.all exercises
    Show solution
    Promise.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.

  11. 109. Read JSON from a response

    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 exercises
    Show solution
    function 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.

  12. 110. Order code and a timer

    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 exercises
    Show solution
    const 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.

JavaScript Classes

  1. 111. Write a class

    Write a Person class that stores a name. Build one with the name Ada and show its name in #out.

    JavaScript Classes exercises
    Show solution
    class 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.

  2. 112. Set two properties

    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 exercises
    Show solution
    class 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.

  3. 113. Write a method with a parameter

    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 exercises
    Show solution
    class 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.

  4. 114. Declare a field

    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 exercises
    Show solution
    class 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.

  5. 115. Write a static method

    Write a class with a static double method. Call it on the class with 5 and show the result in #out.

    JavaScript Static Members exercises
    Show solution
    class 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.

  6. 116. Extend a class

    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 exercises
    Show solution
    class 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.

  7. 117. Call the parent constructor

    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 exercises
    Show solution
    class 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.

  8. 118. Override a method

    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 exercises
    Show solution
    class 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.

  9. 119. Declare a private field

    Write an Account class with a private balance of 100 and a getBalance method. Show the balance in #out.

    JavaScript Private Fields exercises
    Show solution
    class 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.

  10. 120. Write an area getter

    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 exercises
    Show solution
    class 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.

  11. 121. Check an instance

    Write a Dog class and build one. Use instanceof to show whether it is a Dog, true or false, in #out.

    JavaScript instanceof exercises
    Show solution
    class Dog {}
    document.querySelector('#out').textContent = String(new Dog() instanceof Dog);

    The object was built from Dog, so instanceof gives true.

  12. 122. Find the prototype

    Write an Animal class and build one. Show whether its prototype is Animal.prototype, true or false, in #out.

    JavaScript Prototype Chain exercises
    Show solution
    class 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.

JavaScript Type System

  1. 123. Report a string type

    Use typeof to show the type of "hello" in #out.

    JavaScript typeof exercises
    Show solution
    document.querySelector('#out').textContent = typeof "hello";

    Text in quotes is a string.

  2. 124. Convert text to a number

    Given const text = "42", turn it into a number and add 8. Show the result in #out.

    JavaScript Type Conversion exercises
    Show solution
    const text = "42";
    document.querySelector('#out').textContent = String(Number(text) + 8);

    Number("42") is the number 42, so + adds 8.

  3. 125. See plus join

    Use + on the text "5" and the number 3. Show the result in #out.

    JavaScript Type Coercion exercises
    Show solution
    document.querySelector('#out').textContent = "5" + 3;

    One side is text, so 3 becomes text too and they are joined: 53.

  4. 126. Compare loosely

    Compare "5" and 5 with ==. Show loosely equal in #out when they match, otherwise not equal.

    JavaScript == vs === exercises
    Show solution
    document.querySelector('#out').textContent = "5" == 5 ? "loosely equal" : "not equal";

    == turns the text into a number first, so they match. === would not.

  5. 127. Test a non-empty string

    Show text is truthy in #out if "hello" is truthy, otherwise text is falsy.

    JavaScript Truthy and Falsy exercises
    Show solution
    document.querySelector('#out').textContent = "hello" ? "text is truthy" : "text is falsy";

    Text with any character in it is truthy, so the first value is used.

  6. 128. Report an unassigned variable

    Declare a variable with let but give it no value. Show its value in #out.

    JavaScript null and undefined exercises
    Show solution
    let notSet;
    document.querySelector('#out').textContent = String(notSet);

    A variable with no value holds undefined.

  7. 129. Produce a NaN

    Convert "hello" to a number and show the result in #out.

    JavaScript NaN exercises
    Show solution
    document.querySelector('#out').textContent = String(Number("hello"));

    hello is not a number, so the conversion gives NaN.

  8. 130. Copy a number

    Set a to 1 and copy it to b. Change b to 2 and show a in #out.

    JavaScript Primitives and References exercises
    Show solution
    let a = 1;
    let b = a;
    b = 2;
    document.querySelector('#out').textContent = String(a);

    Numbers are copied by value, so a is still 1.

JavaScript Strings

  1. 131. Count the characters

    Show how many characters "Ada Lovelace" has in #out.

    JavaScript Strings exercises
    Show solution
    const name = "Ada Lovelace";
    document.querySelector('#out').textContent = String(name.length);

    Three letters, a space and eight letters make 12.

  2. 132. Insert a value

    Given const name = "Ada", use a template literal to show Hello Ada in #out.

    JavaScript Template Literals exercises
    Show solution
    const name = "Ada";
    document.querySelector('#out').textContent = `Hello ${name}`;

    The part in ${ } is replaced by the value of name.

  3. 133. Escape a quote

    Show She said "hello" in #out, with the quotes, from a string written in double quotes.

    JavaScript String Escape Characters exercises
    Show solution
    document.querySelector('#out').textContent = "She said \"hello\"";

    The backslash tells JavaScript that the quote is part of the text and does not end it.

  4. 134. Uppercase a name

    Given const name = "Ada", show it in capitals in #out.

    JavaScript String Case exercises
    Show solution
    const name = "Ada";
    document.querySelector('#out').textContent = name.toUpperCase();

    toUpperCase returns a copy in capitals.

  5. 135. Check for a word

    Show contains it in #out if "JavaScript Basics" includes Script, otherwise missing.

    JavaScript String Search exercises
    Show solution
    const text = "JavaScript Basics";
    document.querySelector('#out').textContent = text.includes("Script") ? "contains it" : "missing";

    Script is part of JavaScript, so includes gives true.

  6. 136. Take the first characters

    Take the first four characters of "JavaScript" with slice. Show them in #out.

    JavaScript String slice exercises
    Show solution
    const text = "JavaScript";
    document.querySelector('#out').textContent = text.slice(0, 4);

    slice(0, 4) takes positions 0, 1, 2 and 3: Java.

  7. 137. Replace the first match

    Change only the first cat in "cat cat cat" to dog. Show the result in #out.

    JavaScript String replace exercises
    Show solution
    const text = "cat cat cat";
    document.querySelector('#out').textContent = text.replace("cat", "dog");

    replace stops after one match, so the other two cats stay.

  8. 138. Split on a comma

    Split "a,b,c" at the commas. Show how many parts there are in #out.

    JavaScript String split exercises
    Show solution
    const text = "a,b,c";
    document.querySelector('#out').textContent = String(text.split(",").length);

    split gives ["a", "b", "c"], which has 3 items.

  9. 139. Trim the ends

    Remove the spaces round " Ada " with trim. Show the result in #out.

    JavaScript String trim exercises
    Show solution
    const entered = "   Ada   ";
    document.querySelector('#out').textContent = entered.trim();

    trim removes the spaces at both ends and leaves the middle alone.

  10. 140. Join two names

    Given const first = "Ada" and const last = "Lovelace", join them with a space. Show the result in #out.

    JavaScript String Concatenation exercises
    Show solution
    const first = "Ada";
    const last = "Lovelace";
    document.querySelector('#out').textContent = first + " " + last;

    first + " " + last puts the space between the names.

  11. 141. Compare alphabetically

    Show apple first in #out if "apple" comes before "banana", otherwise banana first.

    JavaScript String Comparison exercises
    Show solution
    document.querySelector('#out').textContent = "apple" < "banana" ? "apple first" : "banana first";

    a comes before b, so "apple" < "banana" is true.

  12. 142. Keep the result

    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 exercises
    Show solution
    let text = "hello";
    text = text.toUpperCase();
    document.querySelector('#out').textContent = text;

    toUpperCase returns new text, so it has to be stored to be kept.

JavaScript Numbers & Math

  1. 143. Add ten and three

    Store 10 and 3 in two variables. Show their sum in #out.

    JavaScript Numbers exercises
    Show solution
    const a = 10;
    const b = 3;
    document.querySelector('#out').textContent = a + b;

    Both are numbers, so + adds them.

  2. 144. Round to two decimals

    Show 19.567 with two decimals in #out. Use toFixed.

    JavaScript Number Methods exercises
    Show solution
    const price = 19.567;
    document.querySelector('#out').textContent = price.toFixed(2);

    19.567 rounds to 19.57 with two decimals.

  3. Show solution
    const width = "250px";
    document.querySelector('#out').textContent = String(parseInt(width, 10));

    parseInt reads 250 and stops at p.

  4. 146. See the precision error

    Show exact in #out if 0.1 + 0.2 equals 0.3, otherwise not exact.

    JavaScript Number Precision exercises
    Show solution
    document.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.

  5. 147. Remove the sign

    Show the absolute value of -5 in #out. Use Math.abs.

    JavaScript Math Object exercises
    Show solution
    document.querySelector('#out').textContent = String(Math.abs(-5));

    -5 is five away from 0, so the result is 5.

  6. 148. Round to the nearest

    Round 4.5 to the nearest whole number with Math.round. Show it in #out.

    JavaScript Math Rounding exercises
    Show solution
    document.querySelector('#out').textContent = String(Math.round(4.5));

    4.5 is halfway, and Math.round goes up, to 5.

  7. 149. Check the random range

    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 exercises
    Show solution
    const 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.

  8. 150. Find the largest of three

    Show the largest of 5, 2 and 9 in #out. Use Math.max.

    JavaScript Math.min and Math.max exercises
    Show solution
    document.querySelector('#out').textContent = String(Math.max(5, 2, 9));

    9 is the largest of the three.

  9. 151. Group the digits

    Show 1234567 with commas between the thousands in #out. Use toLocaleString with "en-GB".

    JavaScript Number Formatting exercises
    Show solution
    document.querySelector('#out').textContent = (1234567).toLocaleString("en-GB");

    British English puts a comma after every three digits.

  10. 152. Check for a whole number

    Show an integer in #out if 42.5 is a whole number, otherwise not an integer.

    JavaScript Integer Safety exercises
    Show solution
    document.querySelector('#out').textContent = Number.isInteger(42.5) ? "an integer" : "not an integer";

    42.5 has a decimal part, so it is not an integer.

JavaScript Errors

  1. 153. Catch a failure

    Read the length of null inside try. In catch, set a message to something went wrong and show it in #out.

    JavaScript Errors exercises
    Show solution
    let 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.

  2. 154. Handle bad JSON

    Parse the text not json with JSON.parse inside try. In catch, show could not parse that in #out.

    JavaScript try catch exercises
    Show solution
    let 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.

  3. 155. Throw on bad input

    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 exercises
    Show solution
    function 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.

  4. 156. Clean up after a failure

    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 exercises
    Show solution
    const 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.

  5. 157. Identify a TypeError

    Read the length of null and catch the error. Show the error's name in #out.

    JavaScript Error Types exercises
    Show solution
    let name;
    try {
      null.length;
    } catch (error) {
      name = error.name;
    }
    document.querySelector('#out').textContent = name;

    Reading a property of null is a TypeError.

  6. 158. Create a custom error

    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 exercises
    Show solution
    class 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.

  7. 159. Return a fallback

    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 exercises
    Show solution
    function 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.

  8. 160. Check the types

    Given const a = "10" and const b = 10, show the typeof both in #out, with a space between.

    JavaScript Debugging exercises
    Show solution
    const 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.

JavaScript Map & Set

  1. 161. Store and read a value

    Make a Map and set Ada to 90. Read it back and show it in #out.

    JavaScript Map exercises
    Show solution
    const scores = new Map();
    scores.set("Ada", 90);
    document.querySelector('#out').textContent = String(scores.get("Ada"));

    get("Ada") gives the value stored under Ada.

  2. 162. List the keys of a Map

    Make a Map where Ada is 90 and Grace is 95. Show its keys joined by commas in #out.

    JavaScript Map Methods exercises
    Show solution
    const scores = new Map([["Ada", 90], ["Grace", 95]]);
    document.querySelector('#out').textContent = [...scores.keys()].join(",");

    [...scores.keys()] is ["Ada", "Grace"].

  3. 163. Ignore a duplicate

    Add js, css and js to a Set. Show its size in #out.

    JavaScript Set exercises
    Show solution
    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.

  4. 164. Combine two sets

    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 exercises
    Show solution
    const 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.

  5. 165. Store against an object

    Use an object as a key in a WeakMap and store cached. Read it back and show it in #out.

    JavaScript WeakMap and WeakSet exercises
    Show solution
    const 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.

JavaScript Dates

  1. 166. Build a date

    Build the date January 15 2026 and show its year in #out.

    JavaScript Dates exercises
    Show solution
    const 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.

  2. 167. Format for British readers

    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 exercises
    Show solution
    const 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.

  3. 168. Count the days between

    Show how many days there are from January 1 2026 to January 15 2026 in #out. Subtract the dates.

    JavaScript Date Arithmetic exercises
    Show solution
    const 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.

  4. 169. Read the hours

    Build January 15 2026 at 14:30 UTC. Show its UTC hours in #out.

    JavaScript Date Components exercises
    Show solution
    const 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.

  5. 170. Read a timestamp

    Show the typeof the current timestamp in #out. Use Date.now.

    JavaScript Timestamps exercises
    Show solution
    document.querySelector('#out').textContent = typeof Date.now();

    A timestamp is a plain number.

  6. 171. See a rollover

    Build January 32 2026 with Date.UTC. Show the month number it lands on in #out.

    JavaScript Date Pitfalls exercises
    Show solution
    const 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.

JavaScript Regular Expressions

  1. 172. Test for a word

    Use a regular expression to show found in #out if "a cat sat" contains cat, otherwise missing.

    JavaScript Regular Expressions exercises
    Show solution
    document.querySelector('#out').textContent = /cat/.test("a cat sat") ? "found" : "missing";

    The text contains cat, so test gives true.

  2. 173. Match any digit

    Use a regular expression to show has a digit in #out if "abc1" contains a digit, otherwise no digits.

    JavaScript Regex Characters exercises
    Show solution
    document.querySelector('#out').textContent = /\d/.test("abc1") ? "has a digit" : "no digits";

    1 is a digit, so the pattern matches.

  3. 174. Match one or more digits

    Use a regular expression to get the whole number out of "room 42". Show it in #out.

    JavaScript Regex Quantifiers exercises
    Show solution
    document.querySelector('#out').textContent = "room 42".match(/\d+/)[0];

    \d+ takes both digits. \d alone would stop at 4.

  4. 175. Anchor both ends

    Use a regular expression to show accepted in #out if "abc2026xyz" is exactly four digits, otherwise rejected.

    JavaScript Regex Anchors exercises
    Show solution
    document.querySelector('#out').textContent = /^\d{4}$/.test("abc2026xyz") ? "accepted" : "rejected";

    There are letters round the digits, so the anchored pattern does not match.

  5. 176. Capture the year

    Use a regular expression with a group to get the year out of "2026-01-15". Show it in #out.

    JavaScript Regex Groups exercises
    Show solution
    document.querySelector('#out').textContent = "2026-01-15".match(/(\d{4})-(\d{2})-(\d{2})/)[1];

    The first group holds the four digits before the dash.

  6. 177. Find the first digit

    Use search to show the position of the first digit in "abc 1" in #out.

    JavaScript Regex Methods exercises
    Show solution
    document.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.

  7. 178. Accept digits only

    Use a regular expression to show accepted in #out if "12345" is nothing but digits, otherwise rejected.

    JavaScript Regex Validation exercises
    Show solution
    document.querySelector('#out').textContent = /^\d+$/.test("12345") ? "accepted" : "rejected";

    Every character is a digit, so the pattern matches the whole text.

  8. 179. Collapse the whitespace

    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 exercises
    Show solution
    document.querySelector('#out').textContent = "a   b\t\tc".replace(/\s+/g, " ");

    Each run, however long, is replaced by one space.

JavaScript Storage & BOM

  1. 180. Save and read a value

    Save Ada under the key name in localStorage. Read it back and show it in #out.

    JavaScript localStorage exercises
    Show solution
    localStorage.setItem("name", "Ada");
    document.querySelector('#out').textContent = localStorage.getItem("name");

    getItem("name") gives the saved text.

  2. 181. Save for this tab

    Save 2 under the key step in sessionStorage. Read it back and show it in #out.

    JavaScript sessionStorage exercises
    Show solution
    sessionStorage.setItem("step", "2");
    document.querySelector('#out').textContent = sessionStorage.getItem("step");

    The value stays until the tab is closed.

  3. 182. Save an object

    Save { name: "Ada", age: 36 } in localStorage as JSON. Read it back and show the name in #out.

    JavaScript Storing Objects exercises
    Show solution
    const 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.

  4. 183. No event in the same tab

    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 exercises
    Show solution
    let 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.

  5. Show solution
    document.querySelector('#out').textContent = typeof window;

    window is an object that holds everything in the page.

  6. 185. Read the host

    Parse "https://example.com/products?id=42" with new URL. Show its host in #out.

    JavaScript location Object exercises
    Show solution
    const 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.

  7. 186. Check pushState exists

    Show the typeof history.pushState in #out.

    JavaScript history Object exercises
    Show solution
    document.querySelector('#out').textContent = typeof history.pushState;

    pushState is a method, so its type is function.

  8. Show solution
    document.querySelector('#out').textContent = typeof navigator.onLine;

    onLine is true or false, which is the type boolean.

JavaScript Modules

  1. 188. Keep a value private

    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 exercises
    Show solution
    const 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.

  2. 189. Export two named values

    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 exercises
    Show solution
    const 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.

  3. 190. Import a named value

    Make an object named mathModule with a double function. Take double out by destructuring and show double(5) in #out.

    JavaScript import exercises
    Show solution
    const 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.

  4. 191. Wait until the page is ready

    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 exercises
    Show solution
    function 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.

  5. 192. Load a module later

    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 exercises
    Show solution
    function 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.

  6. 193. Build a counter module

    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 exercises
    Show solution
    const 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.

JavaScript Generators & Iterators

  1. 194. Call next yourself

    Get the iterator of [1, 2, 3] and show the first value it gives in #out.

    JavaScript Iterators exercises
    Show solution
    const 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.

  2. 195. Check an array is iterable

    Show the typeof an array's Symbol.iterator method in #out.

    JavaScript Iterables exercises
    Show solution
    document.querySelector('#out').textContent = typeof [][Symbol.iterator];

    An array has this method, which is what lets for...of work on it.

  3. 196. Write a generator

    Write a generator function that yields 1, 2 and 3. Show the values joined by commas in #out.

    JavaScript Generator Functions exercises
    Show solution
    function* 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.

  4. 197. Send a value in

    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 exercises
    Show solution
    function* 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.

  5. 198. Make an object iterable

    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 exercises
    Show solution
    const 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.

  6. 199. Take from an endless generator

    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 exercises
    Show solution
    function* 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.

  7. 200. Read an async generator

    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 exercises
    Show solution
    async 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.

JavaScript Performance

  1. 201. Time a block of work

    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 exercises
    Show solution
    const 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.

  2. 202. Build a debounce

    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 exercises
    Show solution
    function 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.

  3. 203. Build a throttle

    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 exercises
    Show solution
    function 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.

  4. 204. Cache a function's result

    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 exercises
    Show solution
    function 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.

  5. 205. Time a function

    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 exercises
    Show solution
    function 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.

  6. 206. Intercept a read

    Make a Proxy round { name: "Ada" } whose get handler returns the property. Show the name read through the proxy in #out.

    JavaScript Proxy exercises
    Show solution
    const 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.

  7. 207. Read with Reflect.get

    Read the name of { name: "Ada" } with Reflect.get. Show it in #out.

    JavaScript Reflect exercises
    Show solution
    const person = { name: "Ada" };
    document.querySelector('#out').textContent = Reflect.get(person, "name");

    Reflect.get does the same as a dot, as a function.

1042 JavaScript exercises in all

The first in every lesson is free. The rest come with the practice plan, and your first month costs nothing.

See the practice plan

Stuck on a topic?

Read the lesson in the JavaScript tutorial, then come back and solve it.

JavaScript tutorial

Need the HTML first?

Practice the tags your scripts will work on.

HTML exercises

Ready for interviews?

Answer JavaScript interview questions.

Interview questions