Convert Decimal to Binary or Hex in JavaScript Based on Condition



Problem

We are required to write a JavaScript function that takes in a number n. Our function should convert the number to binary or hex based on −

  • If a number is even, convert it to binary.
  • If a number is odd, convert it to hex.

Example

Following is the code −

 Live Demo

const num = 1457;
const conditionalConvert = (num = 1) => {
   const isEven = num % 2 === 0;
   const toBinary = () => num.toString(2);
   const toHexadecimal = () => num.toString(16);
   return isEven
      ? toBinary()
      : toHexadecimal();
};
console.log(conditionalConvert(num));

Output

Following is the console output −

5b1
Updated on: 2021-04-20T06:34:14+05:30

180 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements