LearnFrenzy
Sign in Take a free test

Operators · Operators Coding Problems · Question 1

Simple calculator in JavaScript Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Write calculate(a, op, b) for +, -, *, /, % and **, returning "Cannot divide by zero" for division by 0 and "Unknown operator" for anything else.

Solution
main.js
function calculate(a, op, b) {
  switch (op) {
    case "+": return a + b;
    case "-": return a - b;
    case "*": return a * b;
    case "/": return b === 0 ? "Cannot divide by zero" : a / b;
    case "%": return a % b;
    case "**": return a ** b;
    default: return "Unknown operator";
  }
}

const tests = [[12, "+", 5], [12, "-", 5], [12, "*", 5], [12, "/", 5], [12, "%", 5], [2, "**", 8], [7, "/", 0], [3, "^", 2]];
for (const [a, op, b] of tests) {
  console.log(`${a} ${op} ${b} = ${calculate(a, op, b)}`);
}

Output Verified by running it on Node.js

12 + 5 = 17
12 - 5 = 7
12 * 5 = 60
12 / 5 = 2.4
12 % 5 = 2
2 ** 8 = 256
7 / 0 = Cannot divide by zero
3 ^ 2 = Unknown operator

Each case returns, so no break is needed. Dividing by zero would give Infinity rather than an error, which is why it is checked explicitly. ^ is XOR in JavaScript, not a power operator.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links