Testing whether a value is odd or even - javascript

I decided to create simple isEven and isOdd function with a very simple algorithm:
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript.

Use modulus:
function isEven(n) {
return n % 2 == 0;
}
function isOdd(n) {
return Math.abs(n % 2) == 1;
}
You can check that any value in Javascript can be coerced to a number with:
Number.isFinite(parseFloat(n))
This check should preferably be done outside the isEven and isOdd functions, so you don't have to duplicate error handling in both functions.

I prefer using a bit test:
if(i & 1)
{
// ODD
}
else
{
// EVEN
}
This tests whether the first bit is on which signifies an odd number.

How about the following? I only tested this in IE, but it was quite happy to handle strings representing numbers of any length, actual numbers that were integers or floats, and both functions returned false when passed a boolean, undefined, null, an array or an object. (Up to you whether you want to ignore leading or trailing blanks when a string is passed in - I've assumed they are not ignored and cause both functions to return false.)
function isEven(n) {
return /^-?\d*[02468]$/.test(n);
}
function isOdd(n) {
return /^-?\d*[13579]$/.test(n);
}

Note: there are also negative numbers.
function isOddInteger(n)
{
return isInteger(n) && (n % 2 !== 0);
}
where
function isInteger(n)
{
return n === parseInt(n, 10);
}

Why not just do this:
function oddOrEven(num){
if(num % 2 == 0)
return "even";
return "odd";
}
oddOrEven(num);

To complete Robert Brisita's bit test .
if ( ~i & 1 ) {
// Even
}

var isOdd = x => Boolean(x % 2);
var isEven = x => !isOdd(x);

var isEven = function(number) {
// Your code goes here!
if (number % 2 == 0){
return(true);
}
else{
return(false);
}
};

A few
x % 2 == 0; // Check if even
!(x & 1); // bitmask the value with 1 then invert.
((x >> 1) << 1) == x; // divide value by 2 then multiply again and check against original value
~x&1; // flip the bits and bitmask

We just need one line of code for this!
Here a newer and alternative way to do this, using the new ES6 syntax for JS functions, and the one-line syntax for the if-else statement call:
const isEven = num => ((num % 2) == 0);
alert(isEven(8)); //true
alert(isEven(9)); //false
alert(isEven(-8)); //true

A simple modification/improvement of Steve Mayne answer!
function isEvenOrOdd(n){
if(n === parseFloat(n)){
return isNumber(n) && (n % 2 == 0);
}
return false;
}
Note: Returns false if invalid!

Different way:
var isEven = function(number) {
// Your code goes here!
if (((number/2) - Math.floor(number/2)) === 0) {return true;} else {return false;};
};
isEven(69)

Otherway using strings because why not
function isEven(__num){
return String(__num/2).indexOf('.') === -1;
}

if (testNum == 0);
else if (testNum % 2 == 0);
else if ((testNum % 2) != 0 );

Maybe this?
if(ourNumber % 2 !== 0)

var num = someNumber
isEven;
parseInt(num/2) === num/2 ? isEven = true : isEven = false;

for(var a=0; a<=20;a++){
if(a%2!==0){
console.log("Odd number "+a);
}
}
for(var b=0; b<=20;a++){
if(b%2===0){
console.log("Even number "+b);
}
}

Check if number is even in a line of code:
var iseven=(_)=>_%2==0

This one is more simple!
var num = 3 //instead get your value here
var aa = ["Even", "Odd"];
alert(aa[num % 2]);

To test whether or not you have a odd or even number, this also works.
const comapare = x => integer(checkNumber(x));
function checkNumber (x) {
if (x % 2 == 0) {
return true;
}
else if (x % 2 != 0) {
return false;
}
}
function integer (x) {
if (x) {
console.log('even');
}
else {
console.log('odd');
}
}

Using modern javascript style:
const NUMBERS = "nul one two three four five six seven ocho nueve".split(" ")
const isOdd = n=> NUMBERS[n % 10].indexOf("e")!=-1
const isEven = n=> isOdd(+n+1)

function isEven(n) {return parseInt(n)%2===0?true:parseInt(n)===0?true:false}
when 0/even wanted but
isEven(0) //true
isEven(1) //false
isEven(2) //true
isEven(142856) //true
isEven(142856.142857)//true
isEven(142857.1457)//false
​

if (i % 2) {
return odd numbers
}
if (i % 2 - 1) {
return even numbers
}

Related

javascript code, create a function that returns a boolean depending on whether or not a number is even or not?

var i = 1;
var numberCounter = 0
function isEven(num){
if (i % numberCounter === 0) {
console.log('true');
} else { console.log('false');
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
Im not exactly sure where i went wrong here, i am trying to create a function that returns a boolean depending on whether or not a number is even or not.
in order to check if a number is even or not you should check to see if the modulo of 2 with the number is 0. other then that in order to return a value from a function you should use the keyword return. therefor the isEven function should be:
function isEven(num){
return num % 2 === 0;
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
(even number) % 2 = 0 and with ! you will the 0 as 1 in boolean.
% => module
/ => division
const isEven = number => !(number % 2)
isEven(2) // true
const isOdd = number => !!(number % 2)
isEven(3) // true
In your code :
var i = 1;
var numberCounter = 0
function isEven(num){
if (i % numberCounter === 0) {
console.log('true');
} else { console.log('false');
}
Note that i is equal to 0 and numberCounter is equal to 0. No matter which number is passed in your function, its value won't be considered.
You want to define if a number is odd or even. As a matter of fact the number you want to estimate is the parameter of the function.
A basic definition would be that an odd number can be divided by 2. It means that the remainder of the division is equal to 0.
the if statement concerns the num (passed as parameter) and the remainder.
I took your code and modified it. Saar Davidson answer is much more better and effective (in a single line).
function isEven(num){
if (num % 2 === 0) {
console.log('true');
return true;
} else {
console.log('false');
return false;
}
}

Recursive function to determine if number is even or odd by subtracting two from n until n = 0 or 1

Zero is even.
One is odd.
For any other number N, its evenness is the same as N - 2.
Define a recursive function isEven corresponding to this description. The function should accept a single parameter (a positive, whole number) and return a Boolean.
Here is my implementation of isEven:
let isEven = function(n){
even = 0;
odd = 1;
if(n == even){
return true;
}
else if (n == odd) {
return false;
}
else{
n -= 2;
console.log(n); //Used to see value of n through each call
isEven(n);
}
};
When I call this function, it returns undefined
document.write(isEven(50)); //prints `undefined`
The output from console.log(n) is the following:
Failed to load resource: net::ERR_FILE_NOT_FOUND
48
46
...
0
I am not sure why Failed to load resource: net::ERR_FILE_NOT_FOUND is the first output, but after that n is hitting 0, so why is
if(n == even){
return true;
}?
not executing?
You need to return the result from the recursive call.
let isEven = function(n){
const // declare local variables/constants
even = 0,
odd = 1;
if(n == even){
return true;
}
else if (n == odd) {
return false;
}
else{
//n -= 2; no need to reassign a value for a single use
return isEven(n - 2); // return here
}
};
console.log(isEven(50));
console.log(isEven(21));
A better style without else parts, because this is not necessary if returned before.
use values directly, if used only once,
use strict comparison (Identity/strict equality operator ===), because not strict can led to wrong assumptions
take a calculation for the parameter directly without reassign a value to the variable which is not used anymore
let isEven = function(n){
if (n === 0) return true;
if (n === 1) return false;
return isEven(n - 2);
};
console.log(isEven(50));
console.log(isEven(21));
But don't miss out on the opportunity to learn about mutual recursion!
const isEven = (n = 0) =>
n === 0
? true
: isOdd (n - 1)
const isOdd = (n = 0) =>
n === 0
? false
: isEven (n - 1)
console .log
( isEven (0) // true
, isEven (1) // false
, isEven (2) // true
, isEven (3) // false
, isEven (99) // false
)
console .log
( isOdd (0) // false
, isOdd (1) // true
, isOdd (2) // false
, isOdd (3) // true
, isOdd (99) // true
)

powerofTwo algorithm solution

Below is my algo to check if number is a power of two. When I run this algo in test case "2" the answer is false. I want to know why it behaves this way ?
var isPowerOfTwo = function(n) {
if(n === 1){
console.log("i came here");
return true;
}
if(n === 0){
return false;
}
if(n%2 === 0){
console.log(n);
n=n/2;
console.log(n);
isPowerOfTwo(n);
}
if(n%2 === 1){
return false;
}
};
You're not returning the recursive call, and you're also changing n before the tests have finished - if n / 2 resolves to 1 then your reassignment of n will result in the bottom if statement running. Use else instead, and don't reassign n, simply pass n / 2 to the recursive call:
var isPowerOfTwo = function(n) {
if (n === 1) return true;
if (n === 0) return false;
if (n % 2 === 0) return isPowerOfTwo(n / 2);
else return false;
};
console.log(isPowerOfTwo(2));
console.log(isPowerOfTwo(8));
console.log(isPowerOfTwo(6));
Your if (n%2 === 1) return false; condition could result in another bug: what if the initial n was not an integer? Then the function would call itself forever, resulting in an overflow.
Because 1 % 2 === 1
The "problem" is that in the third if you are changing the value of n and not returning any value so it will enter the last if too.
As mentioned, you don't return any value in the 3rd if statement, hence you always get false for values greater than 1 as it will execute the 4th statement too.
In addition to the given answers, here is an interesting solution (initially by Jaromanda X), which I expanded so it deals with if a non-number is passed as a value.
Try cast to a number
const isPowerOfTwo = n => Number(n).toString(2).split('1').length === 2
console.log(isPowerOfTwo(''));
console.log(isPowerOfTwo('0'));
console.log(isPowerOfTwo('1'));
console.log(isPowerOfTwo('2'));
console.log(isPowerOfTwo(2));
console.log(isPowerOfTwo(8));
console.log(isPowerOfTwo(6));
Check the type
const isPowerOfTwo = n => typeof n === 'number' && n.toString(2).split('1').length === 2
console.log(isPowerOfTwo(''));
console.log(isPowerOfTwo('0'));
console.log(isPowerOfTwo('1'));
console.log(isPowerOfTwo('2'));
console.log(isPowerOfTwo(2));
console.log(isPowerOfTwo(8));
console.log(isPowerOfTwo(6));
I think you just need to return an actual value from the n % 2 === 0 branch of your function:
var isPowerOfTwo = function(n) {
if (n === 1) {
console.log("i came here");
return true;
}
else if (n === 0) {
return false;
}
else if (n % 2 === 0) {
console.log(n);
n = n / 2;
console.log(n);
return isPowerOfTwo(n);
}
else { // no need for an if here
return false;
}
};
Note that in the final else we do not need to check anything, because we have already ascertained the number is not a multiple of 2.
Javascript one-liner solution
For any power of 2 (n & n - 1) will return 0. Simple bit-wise operators
isPowerOfTwo = n => !(n & n - 1)
The above function will return true for 0, which is not a power of 2. For that
isPowerOfTwo = n => (n != 0) && !(n & n - 1)

JavaScript: Too much recursion?

I am learning JavaScript through Eloquent JavaScript and one of the exercises is to write a recursive function, isEven, that returns true if a number is even or false if a number is odd.
If I understood correctly, the author specifically wanted the following to be implemented:
If a number == 0, then it is even.
If a number == 1, then it is odd.
"For any number N, its evenness is the same as N-2".
But when I use the code I have below, I get an error: InternalError: too much recursion (line 3 in function isEven) … How can I fix this while still using a recursive function?
// Your code here.
function isEven(n){
if(n==0){
return true;
}
else if(n==1){
return false;
}
else{
n = n-2;
isEven(n);
}
}
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ??
You could add another check, before decrementing/incrementing a value.
function isEven(n) {
if (n == 0) {
return true;
}
if (n == 1) {
return false;
}
if (n > 0) {
n = n - 2;
} else {
n = n + 2;
}
return isEven(n);
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
To handle it recursion with that function, the value needs to be its absolute value.
console.log("isEven");
function isEven(n) {
//Ensure that we look at the numbers absolute value
n = Math.abs(n);
//Do a loop instead of recursion
if (n == 0) {
return true;
} else if (n == 1) {
return false;
} else {
n = n - 2;
return isEven(n);
}
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
console.log("fasterIsEven");
//A faster way that eliminates recursion
function fasterIsEven(n) {
return n % 2 === 0;
}
console.log(fasterIsEven(50));
console.log(fasterIsEven(75));
console.log(fasterIsEven(-1));
Javascript has a build-in method to test if something is dividable with something else, called modulus (%). This method is faster, but not recursive.
function IsEven(n){ return n%2 === 0 }
The core code is this one
return n%2 === 0
In order to increase the program's strength, it is recommended to increase non-number decisions.

How do I know if a number is odd or even in JS? [duplicate]

Can anyone point me to some code to determine if a number in JavaScript is even or odd?
Use the below code:
function isOdd(num) { return num % 2;}
console.log("1 is " + isOdd(1));
console.log("2 is " + isOdd(2));
console.log("3 is " + isOdd(3));
console.log("4 is " + isOdd(4));
1 represents an odd number, while 0 represents an even number.
Use the bitwise AND operator.
function oddOrEven(x) {
return ( x & 1 ) ? "odd" : "even";
}
function checkNumber(argNumber) {
document.getElementById("result").innerHTML = "Number " + argNumber + " is " + oddOrEven(argNumber);
}
checkNumber(17);
<div id="result" style="font-size:150%;text-shadow: 1px 1px 2px #CE5937;" ></div>
If you don't want a string return value, but rather a boolean one, use this:
var isOdd = function(x) { return x & 1; };
var isEven = function(x) { return !( x & 1 ); };
You could do something like this:
function isEven(value){
if (value%2 == 0)
return true;
else
return false;
}
function isEven(x) { return (x%2)==0; }
function isOdd(x) { return !isEven(x); }
Do I have to make an array really large that has a lot of even numbers
No. Use modulus (%). It gives you the remainder of the two numbers you are dividing.
Ex. 2 % 2 = 0 because 2/2 = 1 with 0 remainder.
Ex2. 3 % 2 = 1 because 3/2 = 1 with 1 remainder.
Ex3. -7 % 2 = -1 because -7/2 = -3 with -1 remainder.
This means if you mod any number x by 2, you get either 0 or 1 or -1. 0 would mean it's even. Anything else would mean it's odd.
This can be solved with a small snippet of code:
function isEven(value) {
return !(value % 2)
}
Hope this helps :)
In ES6:
const isOdd = num => num % 2 == 1;
Like many languages, Javascript has a modulus operator %, that finds the remainder of division. If there is no remainder after division by 2, a number is even:
// this expression is true if "number" is even, false otherwise
(number % 2 == 0)
Similarly, if there is a remainder of 1 after division by 2, a number is odd:
// this expression is true if "number" is odd, false otherwise
(number % 2 == 1)
This is a very common idiom for testing for even integers.
With bitwise, codegolfing:
var isEven=n=>(n&1)?"odd":"even";
Use my extensions :
Number.prototype.isEven=function(){
return this % 2===0;
};
Number.prototype.isOdd=function(){
return !this.isEven();
}
then
var a=5;
a.isEven();
==False
a.isOdd();
==True
if you are not sure if it is a Number , test it by the following branching :
if(a.isOdd){
a.isOdd();
}
UPDATE :
if you would not use variable :
(5).isOdd()
Performance :
It turns out that Procedural paradigm is better than OOP paradigm .
By the way , i performed profiling in this FIDDLE . However , OOP way is still prettiest .
A simple function you can pass around. Uses the modulo operator %:
var is_even = function(x) {
return !(x % 2);
}
is_even(3)
false
is_even(6)
true
if (X % 2 === 0){
} else {
}
Replace X with your number (can come from a variable). The If statement runs when the number is even, the Else when it is odd.
If you just want to know if any given number is odd:
if (X % 2 !== 0){
}
Again, replace X with a number or variable.
<script>
function even_odd(){
var num = document.getElementById('number').value;
if ( num % 2){
document.getElementById('result').innerHTML = "Entered Number is Odd";
}
else{
document.getElementById('result').innerHTML = "Entered Number is Even";
}
}
</script>
</head>
<body>
<center>
<div id="error"></div>
<center>
<h2> Find Given Number is Even or Odd </h2>
<p>Enter a value</p>
<input type="text" id="number" />
<button onclick="even_odd();">Check</button><br />
<div id="result"><b></b></div>
</center>
</center>
</body>
Many people misunderstand the meaning of odd
isOdd("str") should be false.
Only an integer can be odd.
isOdd(1.223) and isOdd(-1.223) should be false.
A float is not an integer.
isOdd(0) should be false.
Zero is an even integer (https://en.wikipedia.org/wiki/Parity_of_zero).
isOdd(-1) should be true.
It's an odd integer.
Solution
function isOdd(n) {
// Must be a number
if (isNaN(n)) {
return false;
}
// Number must not be a float
if ((n % 1) !== 0) {
return false;
}
// Integer must not be equal to zero
if (n === 0) {
return false;
}
// Integer must be odd
if ((n % 2) !== 0) {
return true;
}
return false;
}
JS Fiddle (if needed): https://jsfiddle.net/9dzdv593/8/
1-liner
Javascript 1-liner solution. For those who don't care about readability.
const isOdd = n => !(isNaN(n) && ((n % 1) !== 0) && (n === 0)) && ((n % 2) !== 0) ? true : false;
You can use a for statement and a conditional to determine if a number or series of numbers is odd:
for (var i=1; i<=5; i++)
if (i%2 !== 0) {
console.log(i)
}
This will print every odd number between 1 and 5.
Just executed this one in Adobe Dreamweaver..it works perfectly.
i used if (isNaN(mynmb))
to check if the given Value is a number or not,
and i also used Math.abs(mynmb%2) to convert negative number to positive and calculate
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body bgcolor = "#FFFFCC">
<h3 align ="center"> ODD OR EVEN </h3><table cellspacing = "2" cellpadding = "5" bgcolor="palegreen">
<form name = formtwo>
<td align = "center">
<center><BR />Enter a number:
<input type=text id="enter" name=enter maxlength="10" />
<input type=button name = b3 value = "Click Here" onClick = compute() />
<b>is<b>
<input type=text id="outtxt" name=output size="5" value="" disabled /> </b></b></center><b><b>
<BR /><BR />
</b></b></td></form>
</table>
<script type='text/javascript'>
function compute()
{
var enter = document.getElementById("enter");
var outtxt = document.getElementById("outtxt");
var mynmb = enter.value;
if (isNaN(mynmb))
{
outtxt.value = "error !!!";
alert( 'please enter a valid number');
enter.focus();
return;
}
else
{
if ( mynmb%2 == 0 ) { outtxt.value = "Even"; }
if ( Math.abs(mynmb%2) == 1 ) { outtxt.value = "Odd"; }
}
}
</script>
</body>
</html>
When you need to test if some variable is odd, you should first test if it is integer. Also, notice that when you calculate remainder on negative number, the result will be negative (-3 % 2 === -1).
function isOdd(value) {
return typeof value === "number" && // value should be a number
isFinite(value) && // value should be finite
Math.floor(value) === value && // value should be integer
value % 2 !== 0; // value should not be even
}
If Number.isInteger is available, you may also simplify this code to:
function isOdd(value) {
return Number.isInteger(value) // value should be integer
value % 2 !== 0; // value should not be even
}
Note: here, we test value % 2 !== 0 instead of value % 2 === 1 is because of -3 % 2 === -1. If you don't want -1 pass this test, you may need to change this line.
Here are some test cases:
isOdd(); // false
isOdd("string"); // false
isOdd(Infinity); // false
isOdd(NaN); // false
isOdd(0); // false
isOdd(1.1); // false
isOdd("1"); // false
isOdd(1); // true
isOdd(-1); // true
Using % will help you to do this...
You can create couple of functions to do it for you... I prefer separte functions which are not attached to Number in Javascript like this which also checking if you passing number or not:
odd function:
var isOdd = function(num) {
return 'number'!==typeof num ? 'NaN' : !!(num % 2);
};
even function:
var isEven = function(num) {
return isOdd(num)==='NaN' ? isOdd(num) : !isOdd(num);
};
and call it like this:
isOdd(5); // true
isOdd(6); // false
isOdd(12); // false
isOdd(18); // false
isEven(18); // true
isEven('18'); // 'NaN'
isEven('17'); // 'NaN'
isOdd(null); // 'NaN'
isEven('100'); // true
A more functional approach in modern javascript:
const NUMBERS = "nul one two three four five six seven ocho nueve".split(" ")
const negate = f=> (...args)=> !f(...args)
const isOdd = n=> NUMBERS[n % 10].indexOf("e")!=-1
const isEven = negate(isOdd)
One liner in ES6 just because it's clean.
const isEven = (num) => num % 2 == 0;
Subtract 2 to it recursively until you reach either -1 or 0 (only works for positive integers obviously) :)
Every odd number when divided by two leaves remainder as 1 and every even number when divided by zero leaves a zero as remainder. Hence we can use this code
function checker(number) {
return number%2==0?even:odd;
}
How about this...
var num = 3 //instead get your value here
var aa = ["Even", "Odd"];
alert(aa[num % 2]);
This is what I did
//Array of numbers
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,32,23,643,67,5876,6345,34,3453];
//Array of even numbers
var evenNumbers = [];
//Array of odd numbers
var oddNumbers = [];
function classifyNumbers(arr){
//go through the numbers one by one
for(var i=0; i<=arr.length-1; i++){
if (arr[i] % 2 == 0 ){
//Push the number to the evenNumbers array
evenNumbers.push(arr[i]);
} else {
//Push the number to the oddNumbers array
oddNumbers.push(arr[i]);
}
}
}
classifyNumbers(numbers);
console.log('Even numbers: ' + evenNumbers);
console.log('Odd numbers: ' + oddNumbers);
For some reason I had to make sure the length of the array is less by one. When I don't do that, I get "undefined" in the last element of the oddNumbers array.
I'd implement this to return a boolean:
function isOdd (n) {
return !!(n % 2);
// or ((n % 2) !== 0).
}
It'll work on both unsigned and signed numbers. When the modulus return -1 or 1 it'll get translated to true.
Non-modulus solution:
var is_finite = isFinite;
var is_nan = isNaN;
function isOdd (discriminant) {
if (is_nan(discriminant) && !is_finite(discriminant)) {
return false;
}
// Unsigned numbers
if (discriminant >= 0) {
while (discriminant >= 1) discriminant -= 2;
// Signed numbers
} else {
if (discriminant === -1) return true;
while (discriminant <= -1) discriminant += 2;
}
return !!discriminant;
}
By using ternary operator, you we can find the odd even numbers:
var num = 2;
result = (num % 2 == 0) ? 'even' : 'odd'
console.log(result);
Another example using the filter() method:
let even = arr.filter(val => {
return val % 2 === 0;
});
// even = [2,4,6]
So many answers here but i just have to mention one point.
Normally it's best to use the modulo operator like % 2 but you can also use the bitwise operator like & 1. They both would yield the same outcome. However their precedences are different. Say if you need a piece of code like
i%2 === p ? n : -n
it's just fine but with the bitwise operator you have to do it like
(i&1) === p ? n : -n
So there is that.
this works for arrays:
function evenOrOdd(numbers) {
const evenNumbers = [];
const oddNumbers = [];
numbers.forEach(number => {
if (number % 2 === 0) {
evenNumbers.push(number);
} else {
oddNumbers.push(number);
}
});
console.log("Even: " + evenNumbers + "\nOdd: " + oddNumbers);
}
evenOrOdd([1, 4, 9, 21, 41, 92]);
this should log out:
4,92
1,9,21,41
for just a number:
function evenOrOdd(number) {
if (number % 2 === 0) {
return "even";
}
return "odd";
}
console.log(evenOrOdd(4));
this should output even to the console
A Method to know if the number is odd
let numbers = [11, 20, 2, 5, 17, 10];
let n = numbers.filter((ele) => ele % 2 != 0);
console.log(n);

Categories

Resources