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
alertorconsole.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 inNumber(...)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 % 2gives the remainder when dividing by 2.- If remainder is
0, it’s even. - Otherwise it’s odd.
- If remainder is
- We use an
if / else if / elsechain to handle each case.
3. Countdown (Loops)
Learning Objectives
- Use a
forloop - 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
forloop:- Starts at
i = n - Runs while
i >= 1 - Decreases
iby 1 each iteration (i--).
- Starts at
- 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
numbersis an array of numeric values.- We set
maxto the first element as a starting point. - The loop starts at index
1because we already used index0formax. - If
numbers[i]is bigger thanmax, we updatemax. - After the loop,
maxholds 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.htmlfile and include the script at the bottom or in a separate.jsfile.
Learning Objectives
- Select elements from the DOM using
document.getElementById - Change the
.textContentof 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 whoseidis"title"and returns it.- We store that element in
heading. .textContentis 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
cartis an object withnameandprice. totalstarts at0.- In the loop:
cart[i]gives the current item object.cart[i].priceaccesses thepriceproperty.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
celsiusValuesis 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 temperaturecand returns its Fahrenheit equivalent. fahrenheitValuesholds 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
setIntervalto 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
secondsstarts at0.setInterval(callback, 1000)runscallbackevery 1000 milliseconds (1 second).- Inside the callback:
- We log the current value of
seconds. - Then we increment it with
seconds++. - If
secondsbecomes greater than10, we:- Log
"Timer finished!" - Call
clearInterval(intervalId)to stop the interval from running again.
- Log
- We log the current value of
intervalIdis a handle returned bysetInterval, which we need to stop it later.
