10 JavaScript Exercises

1. Sum of Two Numbers (Basics: Variables, Input, Output)

Learning Objectives

  • Declare and use variables
  • Get user input with prompt
  • Convert strings to numbers
  • Show output with alert or console.log

Task

Ask the user for two numbers, add them, and show the result.

Sample Solution

const num1 = Number(prompt("Enter the first number:"));
const num2 = Number(prompt("Enter the second number:"));

const sum = num1 + num2;

alert("The sum is: " + sum);
// or console.log("The sum is:", sum);

Explanation

  • prompt(...) returns a string, so we wrap it in Number(...) to convert it to a number.
  • const sum = num1 + num2; adds the two numeric values.
  • alert(...) pops up the result in a dialog box. console.log(...) would print to the DevTools console.

2. Even or Odd? (Conditionals)

Learning Objectives

  • Use if, else if, else
  • Use modulo operator %
  • Make simple decisions based on conditions

Task

Ask the user for a number and tell them whether it’s even or odd.

Sample Solution

const value = Number(prompt("Enter a whole number:"));

if (isNaN(value)) {
  alert("That is not a valid number.");
} else if (value % 2 === 0) {
  alert(value + " is even.");
} else {
  alert(value + " is odd.");
}

Explanation

  • Number(prompt(...)) converts the input to a number.
  • isNaN(value) checks if the result is not a number.
  • value % 2 gives the remainder when dividing by 2.
    • If remainder is 0, it’s even.
    • Otherwise it’s odd.
  • We use an if / else if / else chain to handle each case.

3. Countdown (Loops)

Learning Objectives

  • Use a for loop
  • Practice counting backwards
  • Log values to the console

Task

Ask the user for a positive number n, then log a countdown from n to 1.

Sample Solution

const n = Number(prompt("Enter a positive integer:"));

if (Number.isInteger(n) && n > 0) {
  for (let i = n; i >= 1; i--) {
    console.log(i);
  }
  console.log("Liftoff!");
} else {
  console.log("Please reload and enter a positive integer.");
}

Explanation

  • Number.isInteger(n) ensures we got a whole number.
  • The for loop:
    • Starts at i = n
    • Runs while i >= 1
    • Decreases i by 1 each iteration (i--).
  • Each iteration logs the current i.
  • After the loop, we log "Liftoff!".

4. Find the Maximum in an Array (Arrays & Loops)

Learning Objectives

  • Create and work with arrays
  • Loop over an array using for
  • Keep track of a “current best” (max value)

Task

Given an array of numbers, find the largest one and log it.

Sample Solution

const numbers = [3, 17, 9, 42, 5, 29];

let max = numbers[0]; // start by assuming the first is the largest

for (let i = 1; i < numbers.length; i++) {
  if (numbers[i] > max) {
    max = numbers[i];
  }
}

console.log("The largest number is:", max);

Explanation

  • numbers is an array of numeric values.
  • We set max to the first element as a starting point.
  • The loop starts at index 1 because we already used index 0 for max.
  • If numbers[i] is bigger than max, we update max.
  • After the loop, max holds the largest number in the array.

5. Greeting Function (Functions & Parameters)

Learning Objectives

  • Define a function with parameters
  • Call a function with arguments
  • Return and/or log values from functions

Task

Write a function greet(name) that prints a personalized greeting, then call it several times with different names.

Sample Solution

function greet(name) {
  console.log("Hello, " + name + "! Welcome to JavaScript.");
}

greet("Alex");
greet("Jordan");
greet("Taylor");

Explanation

  • function greet(name) { ... } defines a reusable block of code that takes one parameter: name.
  • Inside, we build a greeting string using "Hello, " + name + "!".
  • Each call, like greet("Alex"), passes a different argument to the function, so the message changes based on the input.

6. Change Page Text with JavaScript (DOM Basics)

For this one, create a simple index.html file and include the script at the bottom or in a separate .js file.

Learning Objectives

  • Select elements from the DOM using document.getElementById
  • Change the .textContent of an element
  • Make code run after the DOM loads

HTML Setup

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>DOM Exercise</title>
  </head>
  <body>
    <h1 id="title">Original Title</h1>
    <script src="script.js"></script>
  </body>
</html>

script.js Sample Solution

// Select the element with id="title"
const heading = document.getElementById("title");

// Change its text
heading.textContent = "Title updated with JavaScript!";

Explanation

  • document.getElementById("title") looks in the HTML for the element whose id is "title" and returns it.
  • We store that element in heading.
  • .textContent is the text inside the element. Changing it updates what you see on the page.

7. Button Click Counter (Events & State)

Learning Objectives

  • Add a click event listener to a button
  • Keep track of state with a variable
  • Update text on the page each click

HTML Setup

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Click Counter</title>
  </head>
  <body>
    <button id="clickBtn">Click me!</button>
    <p>You have clicked <span id="count">0</span> times.</p>

    <script src="script.js"></script>
  </body>
</html>

script.js Sample Solution

const button = document.getElementById("clickBtn");
const countSpan = document.getElementById("count");

let count = 0;

button.addEventListener("click", function () {
  count++;
  countSpan.textContent = count;
});

Explanation

  • We select the button and the <span> where the count will appear.
  • let count = 0; sets our starting count.
  • button.addEventListener("click", function () { ... }) runs the function every time the button is clicked.
  • Inside the event handler:
    • count++ increases the counter.
    • countSpan.textContent = count; updates the text on the page.

8. Shopping Cart Total (Objects & Arrays)

Learning Objectives

  • Represent data with objects
  • Store multiple objects in an array
  • Loop over an array of objects
  • Calculate totals

Task

You have a list of cart items, each with a name and price. Calculate the total price.

Sample Solution

const cart = [
  { name: "Book", price: 12.99 },
  { name: "Headphones", price: 29.99 },
  { name: "Sticker Pack", price: 4.5 }
];

let total = 0;

for (let i = 0; i < cart.length; i++) {
  total += cart[i].price;
}

console.log("Cart total:", total.toFixed(2));

Explanation

  • Each item in cart is an object with name and price.
  • total starts at 0.
  • In the loop:
    • cart[i] gives the current item object.
    • cart[i].price accesses the price property.
    • total += cart[i].price; keeps adding prices up.
  • total.toFixed(2) formats the number with 2 decimal places (like money).

9. Transform an Array with map (Higher-Order Functions)

Learning Objectives

  • Use Array.prototype.map
  • Understand callback functions
  • Transform data in an array

Task

Given an array of Celsius temperatures, convert them all to Fahrenheit and log the new array.

Formula: F = C * 9/5 + 32

Sample Solution

const celsiusValues = [0, 10, 20, 30, 40];

const fahrenheitValues = celsiusValues.map(function (c) {
  return c * 9 / 5 + 32;
});

console.log("Celsius:", celsiusValues);
console.log("Fahrenheit:", fahrenheitValues);

Explanation

  • celsiusValues is the original array.
  • .map(...) creates a new array by applying the callback function to every element.
  • The callback function (c) { return c * 9 / 5 + 32; } receives each temperature c and returns its Fahrenheit equivalent.
  • fahrenheitValues holds the transformed values.

You could also write the callback as an arrow function:

const fahrenheitValues = celsiusValues.map(c => c * 9 / 5 + 32);

10. Simple Timer (setInterval & clearInterval)

Learning Objectives

  • Use setInterval to run code repeatedly
  • Stop an interval using clearInterval
  • Work with timing and basic state

Task

Create a simple timer that counts seconds up from 0 to 10, logging each number. When it reaches 10, stop the timer and log a final message.

Sample Solution

let seconds = 0;

const intervalId = setInterval(function () {
  console.log("Seconds:", seconds);
  seconds++;

  if (seconds > 10) {
    console.log("Timer finished!");
    clearInterval(intervalId);
  }
}, 1000); // 1000 ms = 1 second

Explanation

  • seconds starts at 0.
  • setInterval(callback, 1000) runs callback every 1000 milliseconds (1 second).
  • Inside the callback:
    • We log the current value of seconds.
    • Then we increment it with seconds++.
    • If seconds becomes greater than 10, we:
      • Log "Timer finished!"
      • Call clearInterval(intervalId) to stop the interval from running again.
  • intervalId is a handle returned by setInterval, which we need to stop it later.