Comparing integers by taking two numbers in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in two numbers, let’s say num1 and num2.

  • If num1 is greater than num2, our function should return greater.

  • If num2 is greater than num1, our function should return smaller.

  • Otherwise, the function should return equal.

Example

Following is the code −

const compareIntegers = (num1, num2) => {
   if(typeof num1 !== 'number' || typeof num2 !== 'number'){
      return false;
   };
   if(num1 > num2){
      return 'greater';
   }else if(num2 > num1){
      return 'smaller';
   }else{
      return 'equal';
   };
};
console.log(compareIntegers(12, 56));
console.log(compareIntegers(72, 56));
console.log(compareIntegers(12, 12));
console.log(compareIntegers(12, 33));

Output

Following is the output on console −

smaller
greater
equal
smaller
raja
Published on 10-Dec-2020 07:58:16
Advertisements