JavaScript exercises for beginners, solved and explained (runnable in your browser)
You learn JavaScript by doing it: write a couple of lines, hit run, look at the result. The nice part is that it runs in the browser with nothing to install — exactly like these six exercises, which you can run and edit right here with "Try it". They go from easy to harder: do them all and you will already hold the basics.
Exercise 1 — Greet the user
Print a personalised greeting.
let name = "Julia";
console.log("Hi, " + name + "! Welcome.");console.log shows a value; strings are joined with +. Change the name and run it again.
Exercise 2 — Sum of two numbers
Add two numbers and show the result.
let a = 8;
let b = 5;
console.log("The sum is " + (a + b));Mind the parentheses around a + b: without them, JavaScript would "glue" the numbers as text instead of adding them. Try removing them.
Exercise 3 — Even or odd
Say whether a number is even or odd.
let number = 7;
if (number % 2 === 0) {
console.log(number + " is even");
} else {
console.log(number + " is odd");
}% is the remainder of a division: if dividing by 2 gives remainder zero, the number is even. === compares two values (in JavaScript always use three equals signs).
Exercise 4 — Count from 1 to 5
Print every number from 1 to 5.
for (let i = 1; i <= 5; i++) {
console.log(i);
}i++ increases i by one each round; the loop continues while i <= 5. Change the 5 and see what happens.
Exercise 5 — Sum of the first 100 numbers
Add every number from 1 to 100.
let total = 0;
for (let i = 1; i <= 100; i++) {
total = total + i;
}
console.log("The sum from 1 to 100 is " + total);Here you accumulate: start at zero and add the current number each round. It is the basic pattern of almost any calculation.
Exercise 6 — Find the largest
Find the biggest number in an array.
let numbers = [3, 9, 2, 15, 7];
let biggest = numbers[0];
for (let n of numbers) {
if (n > biggest) {
biggest = n;
}
}
console.log("The largest is " + biggest);Start with the first as the "reigning champion" and replace it whenever you find a bigger one. When this pattern feels natural, you have made a real leap.
What next?
If you enjoyed these, the JavaScript path has hundreds more like them, from your first console.log to objects, arrays, the DOM and async: short theory then immediate practice in the browser, with XP and streaks. The first chapters are free. Just want to experiment? The playground is open.