Thuta Learning
JavaScript
ExercisesProgrammingBeginner

Practice: JS Fundamentals

JavaScriptLesson 5035 min

What you'll walk away with

  • Write input and expected-output cases before writing a function
  • Find edge cases such as 0, an empty array, negative numbers and boundary values
  • Use if/else, for loops, the % operator and forEach correctly in small tasks
  • Explain why two arrays cannot be compared with ===

Explain it simply

Explain it simply

This lesson teaches nothing new. You will write the variables, operators, if/else, loops, functions and arrays of objects from the JS Basics, Control Flow and Core Concepts chapters again and again until they come out naturally.

Football players do not take their first penalty in a real match. They take hundreds on the training ground, so in the match they shoot without thinking. Write each task yourself and check the result yourself. Give each one at least ten minutes of your own effort before you look at a solution.

Problem → Why → Solution

The problem: one input works, so it must be done

The most common beginner habit is to write a function, run it with one input, see the right answer and move on. Try the classifyNumber() below with 5 and you get "positive", so it feels finished. But pass it 0 and both if conditions are false; the function ends without reaching a return statement, so it returns undefined.

The Pass/Fail checker has the same kind of bug. The requirement says "50 and above passes", but the code says > 50, so Cho, who scored exactly 50, fails. If you only ever test 72 and 45, you will never see it.

untested.js
function classifyNumber(num) {
  if (num > 0) return "positive";
  if (num < 0) return "negative";
}

console.log(classifyNumber(5));  // positive - "it works!"
console.log(classifyNumber(0));  // undefined - the case nobody tried

const students = [{ name: "Cho", score: 50 }];
students.forEach((s) => console.log(s.score > 50 ? "Pass" : "Fail")); // 50 -> Fail

Why do these bugs slip through?

Most bugs do not live in ordinary inputs; they hide at the edges: 0, an empty array, negative numbers, and the exact number named in the requirement (here, 50). If you never write the expected results down in advance, you never stop to ask which inputs deserve a test.

Core concept: cases first, code second

The point of fundamentals practice is not memorising syntax. It is learning to reason step by step from an input to an output. The best way to train that is to work through every task in the same order.

1. Write the cases first

Before writing any code, write about three pairs of input and expected output. For Task 1 that is 0 → 32, 37 → 98.6 and -40 → -40. Minus forty is where Celsius and Fahrenheit meet, which makes it an excellent check of the formula.

2. Hunt for the edges

Beyond one ordinary case, add 0, an empty array, a negative number, and the exact number in the requirement: for "50 and above", test 50 itself.

3. Write the smallest function that passes

Write only what the cases need. The function must return its value instead of just printing it with console.log() inside; only a returned value can be checked by check().

4. Check, then tidy up

Run every case. When one fails, fix the code, not the case, unless you are sure the case itself is wrong. Only when everything passes do you refactor: better names, less repetition.

The check() helper turns actual and expected into strings with JSON.stringify() before comparing them. That is necessary because === on two arrays compares their place in memory (their references), not their contents, so [2, 4] === [2, 4] is false. For plain numbers, strings and arrays, JSON.stringify() is good enough.

Say the output out loud before you run

Before pressing Run, write "this prints 98.6" on paper or say it out loud. Without a prediction, every result looks plausible enough, and bugs slip past while you nod along.

Mental model: predict, write, verify
  1. Write the expected output first
  2. Add the edge cases
  3. Write a function that returns
  4. Run check() and read PASS/FAIL

A mismatch between prediction and result is good news: you just found the exact spot where your mental model and JavaScript disagree.

General pattern

javascript
// 1. Write the cases before the code: input -> expected output
// 2. Implement the smallest function that could pass them
function solve(input) {
  // ...
}
// 3. Run every case, including the edges: 0, [], negatives, the boundary
check("solve(normal)", solve(normalInput), expectedValue);
check("solve(edge)", solve(edgeInput), expectedEdgeValue);

Every task follows these three moves: write the cases, write the smallest function, and run all the cases, edges included, through check().

Worked answers to Tasks 1-4, with checks

The four tasks: Task 1, write the Celsius-to-Fahrenheit formula with operators. Task 2, classify a number as positive, negative or zero with if/else and return a string. Task 3, use a for loop to push the even numbers from 1 to 20 into an array. Task 4, loop over a student array with forEach and print Fail below 50 and Pass from 50 upwards. Try them yourself before reading the answers.

fundamentals-1-4.js
// Worked answers for Tasks 1-4, each checked against cases written first.
function check(label, actual, expected) {
  const same = JSON.stringify(actual) === JSON.stringify(expected);
  console.log(`${same ? "PASS" : "FAIL"} ${label} -> ${JSON.stringify(actual)}`);
}

// Task 1: Celsius to Fahrenheit with operators
function celsiusToFahrenheit(celsius) {
  return (celsius * 9) / 5 + 32;
}
check("celsiusToFahrenheit(0)", celsiusToFahrenheit(0), 32);
check("celsiusToFahrenheit(37)", celsiusToFahrenheit(37), 98.6);
check("celsiusToFahrenheit(-40)", celsiusToFahrenheit(-40), -40);

// Task 2: classify with if / else if / else
function classifyNumber(num) {
  if (num > 0) return "positive";
  else if (num < 0) return "negative";
  else return "zero";
}
check("classifyNumber(7)", classifyNumber(7), "positive");
check("classifyNumber(-3)", classifyNumber(-3), "negative");
check("classifyNumber(0)", classifyNumber(0), "zero");

// Task 3: even numbers from 1 to 20 with a for loop
const evenNumbers = [];
for (let i = 1; i <= 20; i++) {
  if (i % 2 === 0) evenNumbers.push(i);
}
check("evenNumbers", evenNumbers, [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]);

// Task 4: Pass from 50 upwards, Fail below 50
const students = [
  { name: "Aye", score: 72 },
  { name: "Bo", score: 45 },
  { name: "Cho", score: 50 },
];
students.forEach((student) => {
  const status = student.score >= 50 ? "Pass" : "Fail";
  console.log(`${student.name}: ${student.score} ${status}`);
});

Code breakdown

  1. A tiny test helperconst same = JSON.stringify(actual) === JSON.stringify(expected);

    Converting both sides to strings first lets Task 3's array be compared by content, and it works for the number and string cases too.

  2. Operator order in the formulareturn (celsius * 9) / 5 + 32;

    Multiplying by 9 before dividing by 5 gives exactly 333 / 5 = 66.6 for 37. Writing 37 * (9 / 5) instead prints 98.60000000000001, because 1.8 has no exact binary floating-point form.

  3. A final else for the leftover caseelse return "zero";

    Whatever is neither positive nor negative must be 0, and the final else catches it, so the function can never fall through to undefined.

  4. Remainder for even numbersif (i % 2 === 0) evenNumbers.push(i);

    % gives the remainder after division; a remainder of 0 when dividing by 2 means even. The loop runs from 1 up to and including 20, hence <=.

  5. The boundary belongs to Passconst status = student.score >= 50 ? "Pass" : "Fail";

    The requirement says "50 and above", so the operator is >=. Cho's score was changed to exactly 50 so the boundary is actually tested.

You should see
PASS celsiusToFahrenheit(0) -> 32
PASS celsiusToFahrenheit(37) -> 98.6
PASS celsiusToFahrenheit(-40) -> -40
PASS classifyNumber(7) -> "positive"
PASS classifyNumber(-3) -> "negative"
PASS classifyNumber(0) -> "zero"
PASS evenNumbers -> [2,4,6,8,10,12,14,16,18,20]
Aye: 72 Pass
Bo: 45 Fail
Cho: 50 Pass

When you are stuck on a task

Solve it by hand first

Work one input through on paper with no computer. For findMax([3, 9, 2]), write "largest so far is 3; 9 is bigger, so 9; 2 is not bigger". Those words become the body of your loop.

Print the variables

Temporarily add a line such as console.log(i, total) inside the loop and watch what happens on each pass. Remove it once you have found the problem.

Shrink the problem

If five elements fail, try one element, then two. The smallest failing input usually reveals the cause of the bug.

In real projects

In real projects

This check() helper is a miniature version of testing tools such as Jest, Vitest or Node's built-in node:test. Professional developers work the same way every day: write the expected value first, then compare it with the actual one. Building that habit now makes moving to a real testing tool later almost effortless.

In business rules such as tax calculation, discounts or exam grading, a boundary bug can cost money or trust. Whether "a discount above 100,000" includes exactly 100,000 is a question for whoever wrote the requirement, and the answer belongs in a test case rather than in a guess buried in the code. In coding interviews, naming the edge cases yourself is also one of the things that earns points.

Common mistakes

Common mistakes

Missing a branch and returning undefined

Writing only if statements and forgetting the case where none match makes the function return undefined, which is more dangerous precisely because no error appears. Always finish with an else or a final return.

Mixing up > and >= at the boundary

"50 and above" means >= 50, while "over 50" means > 50. One word changes a student's result, so always include the boundary value itself as a test case.

Comparing arrays with ===

evenNumbers === [2, 4, 6, ...] is false even when the contents match, because the two arrays are separate objects in memory. Compare their JSON.stringify() forms, or check element by element.

Expecting exact decimals from floating point

0.1 + 0.2 is 0.30000000000000004, and merely reordering a formula's operators can shift a result slightly. Round decimal results, for example with Math.round(x * 10) / 10, before comparing them.

Mini challenge

Tasks 5-8: write the cases, then the code

Write the check() helper yourself and solve four functions: sumArray() adds an array of numbers, countVowels() counts vowels, findMax() finds the largest number, and gradeLetter() turns a score into a letter grade. Write each function's cases before its code.

  • sumArray([]) returns 0
  • countVowels() ignores upper and lower case
  • findMax([]) returns null and findMax([-5, -2]) returns -2
  • gradeLetter() returns "invalid" for non-numbers or scores outside 0-100
fundamentals-5-8.js
function check(label, actual, expected) {
  // TODO: print PASS or FAIL, the label and the actual value
}

function sumArray(numbers) {
  // TODO (Task 5): add every number; an empty array gives 0
}

function countVowels(text) {
  // TODO (Task 6): count a, e, i, o, u in any letter case
}

function findMax(numbers) {
  // TODO (Task 7): return the largest number, or null for []
  //   careful: starting from 0 gives the wrong answer for [-5, -2]
}

function gradeLetter(score) {
  // TODO (Task 8): "invalid" for non-numbers or outside 0-100,
  //   then A (80+), B (65+), C (50+), otherwise F
}

// TODO: write the expected results FIRST, then call check() for each,
//   including [], [-5, -2], 80 (a boundary) and the string "90"

Expected: All eleven cases print PASS: sumArray([]) is 0, countVowels("JavaScript") is 3, findMax([-5, -2]) is -2, gradeLetter(80) is "A" and gradeLetter("90") is "invalid".

Show hint

In findMax(), start max at numbers[0] rather than 0. In gradeLetter(), Number.isFinite() returns false for strings, NaN and Infinity alike, so one check catches every invalid input.

Show solution
fundamentals-5-8.js
function check(label, actual, expected) {
  const same = JSON.stringify(actual) === JSON.stringify(expected);
  console.log(`${same ? "PASS" : "FAIL"} ${label} -> ${JSON.stringify(actual)}`);
}

// Task 5: add up an array (an empty array sums to 0)
function sumArray(numbers) {
  let total = 0;
  for (const n of numbers) total += n;
  return total;
}

// Task 6: count vowels, ignoring upper/lower case
function countVowels(text) {
  let count = 0;
  for (const ch of text.toLowerCase()) {
    if ("aeiou".includes(ch)) count++;
  }
  return count;
}

// Task 7: largest number, or null for an empty array
function findMax(numbers) {
  if (numbers.length === 0) return null;
  let max = numbers[0]; // not 0: [-5, -2] must give -2
  for (const n of numbers) {
    if (n > max) max = n;
  }
  return max;
}

// Task 8: letter grade with input validation
function gradeLetter(score) {
  // Number.isFinite rejects strings, NaN and Infinity in one check
  if (!Number.isFinite(score) || score < 0 || score > 100) return "invalid";
  if (score >= 80) return "A";
  if (score >= 65) return "B";
  if (score >= 50) return "C";
  return "F";
}

check("sumArray([4, 6, 10])", sumArray([4, 6, 10]), 20);
check("sumArray([])", sumArray([]), 0);
check('countVowels("JavaScript")', countVowels("JavaScript"), 3);
check('countVowels("RHYTHM")', countVowels("RHYTHM"), 0);
check("findMax([3, 9, 2])", findMax([3, 9, 2]), 9);
check("findMax([-5, -2])", findMax([-5, -2]), -2);
check("findMax([])", findMax([]), null);
check("gradeLetter(80)", gradeLetter(80), "A");
check("gradeLetter(49)", gradeLetter(49), "F");
check('gradeLetter("90")', gradeLetter("90"), "invalid");
check("gradeLetter(NaN)", gradeLetter(NaN), "invalid");

Quick quiz 1 / 3

In the problem section's classifyNumber() (only two ifs), what does classifyNumber(0) return?

Quick quiz 2 / 3

What does console.log([2, 4] === [2, 4]) print?

Quick quiz 3 / 3

Which set of scores best tests Task 4, "50 and above passes"?

What to remember

  • Write input and expected-output cases before the code
  • Always try 0, an empty array, a negative number and the boundary value itself
  • Functions should return their value; never forget the final else or return
  • Compare arrays by content, not with ===
  • Round decimal results before comparing them

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Practice: JS Fundamentals | Thuta Learning