LearnFrenzy
Sign in Take a free test

Functions · Functions Coding Problems · Question 1

Area calculator with default parameters in JavaScript Solution, output & explanation

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

Write area(shape, a, b) for "square", "rectangle", "circle" and "triangle", where b defaults to a (so a rectangle with one side is a square), and return a message for unknown shapes.

Solution
main.js
function area(shape, a, b = a) {
  switch (shape) {
    case "square": return a * a;
    case "rectangle": return a * b;
    case "circle": return +(Math.PI * a * a).toFixed(2);
    case "triangle": return 0.5 * a * b;      // base a, height b
    default: return `Unknown shape: ${shape}`;
  }
}

console.log(area("square", 5));
console.log(area("rectangle", 4, 6));
console.log(area("rectangle", 4));
console.log(area("circle", 3));
console.log(area("triangle", 10, 7));
console.log(area("hexagon", 2));

Output Verified by running it on Node.js

25
24
16
28.27
35
Unknown shape: hexagon

b = a uses the earlier parameter as a default. +(…).toFixed(2) rounds to two decimals and converts the string back to a number.

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