Home > Enterprise >  How can I add 2 and 4 to odd numbers in JavaScript?
How can I add 2 and 4 to odd numbers in JavaScript?

Time:11-07

I am a beginner in Javascript now I have started, the only background I have is HTML and CSS. I'm trying to make a program that prints whether a number is even or odd. But to the odd numbers to add 2 and 4. My code :

function isEvenExceptTwoOrFour(number) { 
if (number%2 == 0  ) { 
 
 
    console.log("The number is even");}

 
else { 
    console.log("The number is odd ") 
} 
 
} 

CodePudding user response:

You could write an if..else statement like this, using Logical Or (||) to check each of your conditions.

Below I used the statement

if (number === 2 || number === 4 || number % 2 === 1)

This checks if number === 2 or number === 4 or number % 2 === 1 (if the number is odd)

Code:

function isEvenExceptTwoOrFour(number) { 
  if (number === 2 || number === 4 || number % 2 === 1) {
    console.log("Number is considered odd");
  } else {
    console.log("Number is considered even")
  }
}

isEvenExceptTwoOrFour(1);
isEvenExceptTwoOrFour(2);
isEvenExceptTwoOrFour(6);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Write a function that accepts an array of exceptions, and returns a new function that accepts a number. The closure (the function that's returned) will then 1) check to see if the number is in the array, and return false otherwise 2) check to see if the number is even, and return true, otherwise 3) return false.

// Pass in the exceptions array and return a function
// that will accept a number
function checkIsEvenExcept(exceptions) {
  return function (n) {
    if (exceptions.includes(n)) return false;
    return n % 2 === 0 && true;
    return false;
  }
}

const exceptions = [2, 4, 18];

// Assign the result of calling `checkIsEvenExcept` with the
// exceptions array to a variable. This will be the function that
// we can call
const isEven = checkIsEvenExcept(exceptions);

// We can now call that function with a number
// that we need to check
console.log(isEven(6));
console.log(isEven(2));
console.log(isEven(1));
console.log(isEven(4));
console.log(isEven(8));
console.log(isEven(18));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can just add conditions whether the number is 2 or 4.

 function isEvenExceptTwoOrFour(number) { 
   if ( number === 2 || number === 4 ||| number % 2 !== 0){
      console.log("The number is odd ") 
      return 
   }
   console.log("The number is even") 
} 
  • Related