LearnFrenzy
Sign in Take a free test

Arrow Functions · Arrow Functions Coding Problems · Question 1

Rewrite utility functions as arrow functions in JavaScript Solution, output & explanation

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

Rewrite five small utilities (isEven, clamp, initials, toPair, average) as arrow functions using implicit returns wherever possible, and test them.

Solution
main.js
const isEven = (n) => n % 2 === 0;
const clamp = (n, min, max) => Math.min(max, Math.max(min, n));
const initials = (name) => name.split(" ").map((w) => w[0].toUpperCase()).join("");
const toPair = (key, value) => ({ [key]: value });          // object literal: parentheses
const average = (...nums) => (nums.length ? nums.reduce((a, b) => a + b, 0) / nums.length : 0);

console.log(isEven(10), isEven(7));
console.log(clamp(150, 0, 100), clamp(-5, 0, 100), clamp(42, 0, 100));
console.log(initials("sachin ramesh tendulkar"), toPair("city", "Pune"), average(70, 80, 90), average());

Output Verified by running it on Node.js

true false
100 0 42
SRT { city: 'Pune' } 80 0

Every utility is a single expression, so none needs braces or return. The computed key in toPair and the parentheses around the object literal are the two details to watch.

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