Can anyone point me to some code to determine if a number in JavaScript is even or odd?
-
8https://developer.mozilla.org/en/JavaScript/Reference/Operators/Arithmetic_Operators#section_2 – epascarello Feb 16 '11 at 13:01
-
1@DavidThomas I partly agree, but I have two caveats: 1. If I had to choose, I'd rather a beginner programmer knew about the `%` operator than `&`, and 2. While `&` is theoretically faster, [it really doesn't matter](http://jsperf.com/bitwise-and-vs-mod-for-determining-even-or-odd/2). – kojiro Aug 12 '12 at 23:11
-
3@kojiro: I'd rather more (valid) options be presented to a learner; plus I hadn't ever thought to use bitwise-& in this manner before, so it's an interesting take. Anyway, since it *is* a dupe, I've flagged for merger with the pre-existing question. Hopefully, then, the answers here (that particular answer at least), won't be lost. – David Thomas Aug 12 '12 at 23:14
-
1@kojiro I'm afraid to say that your fiddle is quite useless, since most of the computational time is taken by the function calls. But nobody will use a function call to determine if a number is odd or even... I made a third revision of your test, but I'm on my phone now... – MaxArt Aug 13 '12 at 01:05
-
1possible duplicate of [Testing whether a value is odd or even](http://stackoverflow.com/questions/6211613/testing-whether-a-value-is-odd-or-even) – bummi Mar 17 '15 at 14:36
-
`(yourNumber %2==0)` returns `true` if `yourNumber` is **even**. – ashleedawg Dec 11 '19 at 20:31
-
This worked for me, its basic and can be extended at ease: ```const isNumeric = (value = false) => (!!value && !isNaN(value)) && true;``` Returns true for a number and false if not a number. Here's a resource that may be of assistance [JavaScript typeof: Understanding type checking in JavaScript](https://blog.logrocket.com/javascript-typeof-2511d53a1a62/) – 0xe1λ7r Feb 14 '22 at 14:20
-
@DavidThomas using & in a language where the input can be a float or numeric-coercible string is a bad idea; this isn't a strongly typed language – éclairevoyant Jul 20 '22 at 13:53
32 Answers
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.

- 743
- 11
- 21

- 14,540
- 3
- 37
- 44
-
120Note that this will return `0` or `1` (or `NaN` if you feed it something that isn't a number and can't be coerced into one), which will work fine for most situations. But if you want a real `true` or `false`: `return (num % 2) == 1;` – T.J. Crowder Feb 16 '11 at 12:20
-
5yea good note about the NaN. But usually, you want javascript to be truthy or falsey, which is why i wrote it the way i did. – Chii Feb 16 '11 at 12:24
-
10Just to clarify, the modulo operator (%) gives the remainder of a division. So 3%2 would be 3/2, leaving 1 as a remainder, therefore 3%2 will return 1. – Abuh Feb 16 '11 at 12:24
-
6Further to what T.J. said, this will return a fraction if `num` isn't an integer. Which will still work if you compare `isOdd(1.5)==true` (because a fractional value is not equal to `true`), but it would be better if the function returned `true` or `false` as implied by the name "isOdd". – nnnnnn Aug 13 '12 at 02:02
-
10
-
@tfmontague so invert negative numbers first then: `if(num < 0) { num = -num}`. @nnnnnn And I don't know the JS standard library very well, but I'm assuming there's some form of `isinstance(num, integer)` for the case where you are fed a string or a double (in which case I would return false by default, or throw). – Ron Thompson May 28 '16 at 05:53
-
@RonThompson - I've posted a solution below. For negative numbers one can use Math.abs(num), for stings (or non-number data types) one can use isNan(num), and for floats (or doubles) one can use Math.floor(num). – tim-montague May 28 '16 at 06:27
-
@tfmontague yeah, cool. This is old hat stuff with new standard library functions for me. Fun times. – Ron Thompson May 28 '16 at 06:29
-
@nnnnnn - I've provided a solution (at the bottom of the page), that correctly tests for floats, and returns true/false. – tim-montague May 30 '16 at 10:49
-
the correct, fastest way to do this is to use a bitwise &, like in C, it's just testing a bit, i don't see why all those people use the much slower modulo – Martijn Scheffer Nov 25 '19 at 05:28
-
All the above answers may be not fully correct since the minus odd numbers are not considered. e.g., -3 % 2 returns -1. Using **function isOdd(number) { return (number % 2 !== 0);}** should be better. – Ray Chen Mar 17 '21 at 03:56
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 ); };

- 4,001
- 6
- 44
- 75

- 94,763
- 41
- 167
- 253
-
7+1, you're answer definitely beats mine, not to mention that you have the only answer that **does not** use `X % Y`! – s0d4pop Aug 12 '12 at 22:52
-
6I'm not sure if my test is accurate, but the bitwise AND seems to be 40 times slower than the modulo operator for a fixed number and 2 times slower for a random number: http://jsperf.com/odd-or-even – Blender Aug 12 '12 at 22:59
-
9Note that this will return "odd" or "even" for numbers that are not either (e.g., 3.14). – nnnnnn Aug 12 '12 at 23:02
-
2
-
@nnnnnn—yes, the function should test if it's been given a an int first, which will also test if it's a number. See [http://stackoverflow.com/questions/6211613/testing-whether-a-value-is-odd-or-even](http://stackoverflow.com/questions/6211613/testing-whether-a-value-is-odd-or-even) – RobG Aug 12 '12 at 23:22
-
-
7@Gnuey Every number is comprised of a series of bits. All odd numbers have the least-significant (rightmost) bit set to 1, all even numbers 0. The `x & 1` checks if the last bit is set in the number (because 1 Is a number with all bits set to 1 except for the least significant bit): If it *is*, the number is odd, otherwise even. – David G Aug 30 '13 at 13:01
-
1Still not good for not integer numbers. 1.126 will be odd, while 2.127 will be even. – hmartinezd May 13 '14 at 15:17
-
As for speed, nowdays the bitwise is somewhat faster, especially in webkit browsers. – Josiah Mar 16 '15 at 22:17
-
@hmartinezd - Your statement about non-integers isn't correct. (1.126 & 1) returns 1. (2.127 & 1) returns 0. See JSFiddle - https://jsfiddle.net/cf9k0skd/ – tim-montague May 28 '16 at 01:41
-
@Blender - yeah, but when one uses modulus, they also need additional logic to check for strings and negative numbers. The `&` doesn't. So while the actual operator may be slower in performance, it does a lot more. – tim-montague May 28 '16 at 03:52
-
1@tfmontague that's the problem, while 1 is odd, 1.126 isn't, and while 2 is even, 2.127 isn't. – hmartinezd May 29 '16 at 01:16
-
1@hmartinezd - Didn't consider that floats / doubles aren't odd or even. Only integers can be odd or even. Thanks! – tim-montague May 30 '16 at 09:47
-
@hmartinezd - The solution that I've provided (at the bottom of the page) now correctly tests for floats. Thanks. – tim-montague May 30 '16 at 10:46
-
I do not like this on many grounds. & is a bitwise operator, so 2^32 is the highest int that can 'accurately' be deal with for bitwise operators. Using %2 will accurately cater for highest floats up to 2^53. – Rewind Feb 21 '21 at 22:32
You could do something like this:
function isEven(value){
if (value%2 == 0)
return true;
else
return false;
}

- 5,388
- 1
- 26
- 28
-
9It doesn't seem like you know what a boolean is. `if (condition) { answer=true; } else { answer=false; }` is just a needlessly wordy version of `answer = (bool) condition;`. Reduce your function to `function isEven(value) { return (bool) (value%2 == 0); }` and we'll all be happy. – awm Feb 16 '11 at 12:28
-
28
-
8@awm - It seems like _you_ don't know JavaScript. You can't cast to boolean with `(bool)` (that'll give an error) and in any case you don't need to: `return value%2 == 0;` will do the job since the `==` operator returns a boolean. – nnnnnn Aug 13 '12 at 01:55
-
2Wow, did I really write that? Yes, that's obviously wrong; should be something like `answer = !!(condition)`. The point I was trying to make, of course is that you can just `return value%2==0` and don't need to bother with the conditional. – awm Aug 13 '12 at 04:53
-
-
`if (condition) return true; else return false;` isn't a "style difference", it's just bad code in isolation as it's just extra boilerplate for no benefit. Someone new to coding should understand that you can return expressions and variables, not just raw values, and in JS, `value%2==0` is in fact a boolean expression – éclairevoyant Jul 23 '22 at 03:13
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.

- 1,659
- 13
- 15
function isEven(x) { return (x%2)==0; }
function isOdd(x) { return !isEven(x); }

- 36,908
- 70
- 97
- 130
In ES6:
const isOdd = num => num % 2 == 1;

- 15,447
- 5
- 79
- 98

- 1,081
- 1
- 15
- 27
-
4When adding an answer to an eight year old question with 26 existing answers it really is useful to explain what new aspect of the question your answer addresses, and if the passage of time and new versions impacts the answer. A code only answer can almost always be improved by the addition of some explanation and in this case some example calls showing usage. – Jason Aller Jan 13 '20 at 16:06
-
4the title is 'How to determine if a number is odd in JavaScript' and there was no ES6 solution posted for what is asked. – Darryl Mendonez Jan 14 '20 at 14:55
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.

- 58,613
- 19
- 146
- 147
-
3However, modulus can be tricky/undefined for negative values .. be sure to consult the appropriate language specification. – Aug 12 '12 at 22:54
With bitwise, codegolfing:
var isEven=n=>(n&1)?"odd":"even";

- 308
- 3
- 13
-
& bitwise only exactly works on numbers up to 2^32. % works on numbers up to 2^53. – Rewind Feb 21 '21 at 22:55
-
Yes, @Rewind it's only useful for some codegolfing challenges, not for writing production code – Katia Punter Feb 26 '21 at 14:06
-
-
@éclairevoyant I interpreted the question as "show me all different ways of doing odd or even" and I gave a codegolfing answer which I clearly labelled as codegolfing. This means - focus on doing it in as little characters as possible. – Katia Punter Aug 05 '22 at 10:08
-
@KatiaPunter this is a valid method in some other languages but not JS – éclairevoyant Aug 06 '22 at 15:06
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

- 60,309
- 67
- 216
- 347

- 8,969
- 9
- 38
- 49
-
1If your results in the ternary operator are either 'true' or 'false', you really don't need the ternary operator. Here, you could/should just do: `return !(x % 2);` – dom_watson Jun 14 '17 at 08:36
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 .

- 87,526
- 38
- 249
- 254
-
Thanks dude, for this logic, in interviewee someone asked this kind of logic, could not answer, now i got it, thanks.. but is there any benefit in performance by following this method? we could have written isEven(x); etc. – Shoib Mohammed A Dec 28 '15 at 09:43
-
@ShoibMohammedA : Comparison has been done ! http://jsfiddle.net/abdennour/jL2uyksa/3 – Abdennour TOUMI Dec 28 '15 at 11:34
-
-1 don't extend native prototype functions. (http://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice) – tim-montague May 28 '16 at 01:32
<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>

- 139
- 1
- 2
Many people misunderstand the meaning of odd
isOdd("str")
should be false.
Only an integer can be odd.isOdd(1.223)
andisOdd(-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;

- 16,217
- 5
- 62
- 51
-
You can accelerate the solution yet. i.e., in the final statements you can just return !!(n % 2) , this will optionally make it work with signed numbers (i.e., when n % 2 returns 0, it's false, but when -1 or 1 returned, this would return true). Your solution is actually returning false for odd numbers since it's checking if the modulus return is 0, but should check for 1, and 1 would fail for negative numbers, thus return !!(n % 2) is safer. And anyways, {} (block statement) doesn't cause minification issues and is not present in the discussion. – Feb 07 '17 at 17:05
-
@TheProHands - Thanks for the notes. (1) The issue was that the Modulus Version had a typo; it should have been `(n % 2) !== 0` instead of `(n % 2) === 0`. (2) My advice is to avoid `!!(n % 2)`, because (a) it has slower performance than `(n % 2) !== 0` (https://jsperf.com/notnot-vs-strict-not), (b) it's a hack - it coerces a falsey value `0` into `false`, and (c) it's obscure (high-level programming languages shouldn't read like Pascal at the sake of performance - that's the compiler's job). (3) Yes, missing `{}` block statements do result in several issues (as updated in my answer). – tim-montague Feb 08 '17 at 11:17
-
I never avoid block statements because I care about readability, but I'm trying to tell that seeking block statements doesn't result in issues, only in the code maintainace. I.e., using sequence expressions merged with expression statement instead of block statement might make the code unreadable and ugly, i.e.: `if (0) call1(), assign = 0, call2()`, but a single statement isn't bad: `if (0) return; if (0) ;; if (0); break; if (0) continue;`, and anyways I prefer to continue using break-line block statements when I've long-inline conditions. – Feb 08 '17 at 12:04
-
1type/null checks like your `isNaN(n)` are silly - sure you covered the `NaN` case, but `isOdd(null)`, `isOdd(undefined)`, `isOdd({x:1})` all return `false` which I consider to be an error; unless of course you're only specifying that your function has correct behaviour over a given domain: only Number-type inputs. In which case, just drop the `isNaN` check and force the user to call it with the correct type. Defensive programming is awful. Then your function is simplified to `isOdd = x => Math.floor(x) === x && x & 1 === 1` – returning explicit `true` or `false` values is not necessary – Mulan Mar 31 '17 at 08:34
-
`null`, `undefined` and objects `{}` are not odd integers, and therefore the function returns `false` - not sure why you consider that an error. The `isNaN` check is for performance (not for defense), it lets the function exit prematurely without performing the other checks. – tim-montague May 11 '19 at 19:20
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.

- 238
- 2
- 7
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.

- 41
- 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>

- 361
- 3
- 15
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

- 4,263
- 5
- 28
- 47
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

- 100,211
- 27
- 269
- 172
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)

- 8,999
- 2
- 24
- 24
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;
}

- 2,694
- 4
- 22
- 32
How about this...
var num = 3 //instead get your value here
var aa = ["Even", "Odd"];
alert(aa[num % 2]);

- 285
- 2
- 25
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.

- 1,097
- 1
- 16
- 19
-
2It's because the condition is set to less to or equal "<=" to the length of the array. I removed the equal sign and is the result was as desired. – Zakher Masri Mar 16 '15 at 14:27
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;
}
Subtract 2 to it recursively until you reach either -1 or 0 (only works for positive integers obviously) :)

- 3,800
- 3
- 34
- 52
-
-
And it takes a hell of a time when n=2^52, and an infinite amount for n>2^53 – rioV8 Aug 03 '18 at 14:12
By using ternary operator, you we can find the odd even numbers:
var num = 2;
result = (num % 2 == 0) ? 'even' : 'odd'
console.log(result);

- 1,437
- 2
- 26
- 35
Another example using the filter() method:
let even = arr.filter(val => {
return val % 2 === 0;
});
// even = [2,4,6]

- 43
- 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.

- 25,060
- 6
- 56
- 76
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);

- 602
- 2
- 5
- 18
Using higher order functions, you can have an even and a not(even), which is more readable when writing something like unit tests:
function not(f) {
return function(...args) {
let result = f.apply(this, args);
return !result;
};
}
const even = x => x % 2 === 0;
const odd = not(even);
[1,2,3,4,7,7].every(odd)

- 8,014
- 9
- 67
- 101
-
Looks very interesting. Can you help me understand the code? I've tried it out here, but I think I am missing something: https://codepen.io/JannieT/pen/rNqzMgd – Jannie Theunissen May 01 '23 at 07:15