Javascript Logical Operator AND inside 'if' condition - javascript
Inside the if condition, I have num1 and num2 which are checked to see if they can be divided by 2 to determine whether they are odd or not. As you can see, I am checking to see if when divided by 2, whether the answer is 0 or not for both num1 and num2. I'm not sure why it evaluates to true when I enter num2 argument as an even number.
function areBothOdd(num1, num2) {
if(num1 % 2 === 0 && num2 % 2 === 0){
return false;
}
else {
return true;
}
}
var output = areBothOdd(7, 4);
console.log(output); // --> true
Why am I getting true?
And why does this code evaluate as false?
function areBothOdd(num1, num2) {
if(num1 % 2 !== 0 && num2 % 2 !== 0){
return true;
}
else {
return false;
}
}
var output = areBothOdd(7, 4);
console.log(output); // --> false
You need a logical OR ||, instead of an logical AND.
Your test with
num1 % 2 === 0
returns true for even numbers, because even numbers have a remainder of 0 by division with 2.
function areBothOdd(num1, num2) {
if (num1 % 2 === 0 || num2 % 2 === 0) {
return false;
} else {
return true;
}
}
console.log(areBothOdd(7, 4)); // --> false
console.log(areBothOdd(7, 5)); // --> true
console.log(areBothOdd(4, 4)); // --> false
For a check with logical AND, you need to negate the parts and change the logical operator from OR to AND, as the De_Morgan's laws describes the transformation.
num1 % 2 === 0 || num2 % 2 === 0 both parts
num1 % 2 !== 0 && num2 % 2 !== 0 are equal
^^^^ ^^ ^^^
function areBothOdd(num1, num2) {
if (num1 % 2 !== 0 && num2 % 2 !== 0) {
return false;
} else {
return true;
}
}
console.log(areBothOdd(7, 4)); // --> false
console.log(areBothOdd(7, 5)); // --> true
console.log(areBothOdd(4, 4)); // --> false
It always evaluate to true because, what && operator does is to check both condition, if both condition is true than the block will get executed, otherwise else block will get executed.
% will return remainder which will never be zero. in your case while calculate modules i.e 7%2 will result 1.
either you need to use logical !! operator or you can change your condition.
function areBothOdd(num1, num2) {
if(num1 % 2 === 0 && num2 % 2 === 0){
return false;
}
else {
return true;
}
}
var output = areBothOdd(7, 4);
console.log(output);
var x = 7%2;
document.getElementById("demo").innerHTML = x;
<span id="demo"></span>
Because of Short-Circuit evaluation. Simply put, your num2 % 2 === 0 part of condition will not be evaluated. 7 % 2 does not equal to zero hence your function returns true. That's it.
To quote from MDN:
false && (anything) is short-circuit evaluated to false.
true || (anything) is short-circuit evaluated to true.
Note that the anything part of the above expressions is not evaluated,
so any side effects of doing so do not take effect
1st Case :
function areBothOdd(num1, num2) {
if(num1 % 2 === 0 && num2 % 2 === 0){
return false;
}
else {
return true;
}
}
var output = areBothOdd(7, 4);
console.log(output); // --> true
Here, if condition fails as (num1 % 2 === 0 && num2 % 2 === 0) will become (false && true) as 7 is an odd number and 4 is an even number.Hence, it will execute the else block and return true.
2nd Case :
function areBothOdd(num1, num2) {
if(num1 % 2 !== 0 && num2 % 2 !== 0){
return true;
}
else {
return false;
}
}
var output = areBothOdd(7, 4);
console.log(output); // --> false
Here again if condition fails as (num1 % 2 !== 0 && num2 % 2 !== 0) will become (true && false).Hence, it will execute the else block and return false.
Conclusion : As Nina Scholz suggested, use logical OR(||) instead of an logical AND(&&).
DEMO
function areBothOdd(num1, num2) {
if(num1 % 2 === 0 || num2 % 2 === 0){
return false;
}
else {
return true;
}
}
var output = areBothOdd(7, 4);
console.log(output); // --> false
You can change the if condition.In this case,if num1 is odd it doesnot satisfy the if condition and therefore returns true which is else condition.
You can try something like this.
function areBothOdd(int num1,int num2){
if(num1%2 !==0){
if(num2%2!==0){
return true;
}
return false;
}
return false;
}
I'm not sure why it evaluates to true when I enter num2 argument as an even number. Why am I getting true?
There are three possible conditions to consider:
both are odd,
both are even, or
one is odd and one is even
Your first example checks condition 2 (both even) and returns false only for this. Condition 1 and 3 are captured by the else statement and both return true (which is not what you want, you want condition 3 to return false). When providing the numbers 7 and 4, this corresponds to condition 3, which illustrates how the function fails.
And why does this code evaluate as false?
Your second example gets it right, it checks for condition 1 (both odd), and returns true. Otherwise, for condition 2 and 3 it returns false, which is what you want.
Your first code example commented:
function areBothOdd(num1, num2) {
if(num1 % 2 === 0 && num2 % 2 === 0){ // if both are even
return false;
}
else { // otherwise, if one is even or both are odd
return true;
}
}
var output = areBothOdd(7, 4); // one number is even
console.log(output); // --> true
(Note that num % 2 === 0 is a way to test for an even number, and num % 2 !== 0, num % 2, or num & 1 are ways to test for an odd number.)
With a few small changes, the function will work as intended (corresponds to your code example 2):
function areBothOdd(num1, num2) {
if(num1 % 2 && num2 % 2){ // if both are odd
return true;
}
else { // otherwise, if one is even or both are even
return false;
}
}
var output = areBothOdd(7, 4); // one number is even
console.log(output); // --> false
Or just simply:
function areBothOdd(num1, num2) {
return num1 & 1 && num2 & 1
}
Demo code and tests:
function areBothOdd(num1, num2) {
if(num1 % 2 && num2 % 2){ // if both are odd
return true;
}
else { // otherwise, if one is even or both are even
return false;
}
}
// tests
test(1, 1, true); // both are odd
test(2, 2, false); // none are odd
test(1, 2, false); // only one is odd
test(2, 1, false); // only one is odd
// test function
function test(num1, num2, expected) {
console.log(
areBothOdd(num1, num2) == expected ?
'Passes' : 'Fails'
)
}
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; } }
How do I return true or false for ternary operator in Javascript?
I'm trying to convert the code below to a shorthand version with a ternary operator if (sum % 10 === 0) { return true; } else { return false; } It works fine as is, but when I change it to sum % 10 === 0 ? return true : return false; I get a syntax error, and when I change it to sum % 10 === 0 ? true : false; it doesn't work as intended. If anyone can enlighten me as to what's going on, I'd be much appreciated.
The expression (sum % 10 === 0) is boolean itself, so just return it: return sum % 10 === 0
You can simply do: return !(sum % 10) if (sum % 10) === 0, then !(sum % 10) will return true, else false.
What you tried: sum % 10 === 0 ? return true : return false; This does not work, because return is a statement and not an expression. A statement can not be used inside of an expression. sum % 10 === 0 ? true : false; This works, but without a return statement, it is just an expression without using it. Finally, you need to retur the result of the conditional (ternary) operator ?:, like return sum % 10 === 0 ? true : false; For a shorter approach you could return the result of the comparison without ternary. return sum % 10 === 0;
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)
Writing a function that determines if both integers a user enters are odd numbers
How would you write a function that determines if the two numbers a user enters is both odd and returns a boolean value that is true if both numbers are odd? I already know how to write a function that determines if the two numbers a user enters is even or not.
Try: function bothOdd(num1, num2) { if (num1 % 2 == 1 && num2 % 2 == 1) { return true; } return false; } window.alert(bothOdd(1, 2)); window.alert(bothOdd(1, 1));
That pretty easy and simple numbersOdd(1,2); // return false numbersOdd(14, 222); // return true; function numbersOdd(n1, n2) { return n1%2 === 1 && n2%2 === 1; }
Testing whether a value is odd or even
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 }