javascript or operation returns unexpected result - javascript

I am very new to javascript. I have a programm like:
var a = 2
if(a !=2 || a != 3){
console.log("not")
}
Here I have set the variable a value to 2.
In my condition I have set if a is not 2 or a is not 3 it should print not
But here a's value being 2 it is printing not.
It always give not whatever the value is
I can check this is python easily like:
if not a == 2 or not a== 3
Whats wrong in here ??

var a = 2
a is now 2.
a !=2
This is false, so we look on the other side of the or
a != 3
This is true. So one of the two sides of the or test is true. Therefore the or test is true.
If you want to test if a value is not 2 and it is also not 3, then you need to use an && operator.

Maybe you want this:
if(a !=2 && a != 3){
console.log("not")
}
In other words, if a is not 2 AND a is not 3.
This is just how boolean logic works. In your example, because a does not equal 3, the condition is true.

Please read how logical operators work.
Your condition evaluates to true if a is not 2 or a is not 3, that means that is will be false only when a is both 2 and 3 at the same time which isn't possible - this condition will always be true.
You might be also interested in reading something on mathematical logic and negations.
If you want to ensure that a is not 2 or 3 then you should change it to
if((a != 2) && (a != 3)){
as in a is not 2 and a is not 3 - keep in mind that you are working with 2 statements.

Simple explanation
false || true = true
a != 2 //returns false
a != 3 //returns true
In python:
not a == 2 // returns false
not a == 3 //returns true

"OR" in the condition means that the statement in the if block will get executed if any one of the equations out of
(a != 2)
and
(a != 3)
returns true.
In your code snippet
(a != 3)
is true and hence the statement
console.log("not");
gets executed.

This is very expected behaviour and it work same in python and javascript
a = 2
if not a == 2 or not a== 3:
print ("not")
is equivalent to
var a = 2
if(a !=2 || a != 3){
console.log("not")
}

in or expression conditions check while one of theme be come true or until there was no condition.

Related

JavaScript Ternary with Logical OR

var a = '1';
console.log(a == ('2'||'1')?'hi':'hello');
Doing so the condition get failed as a = 1 .
It is comparing a's value 1 with 2 as this condition failed. so it always print hello.
Is there any way to check for value('1') also which is after "||" so that it print hi?
Either list the different possibilities out separately:
a === '2' || a === '1' ? 'hi' : 'hello'
Or use an array and .includes:
['2', '1'].includes(a) ? 'hi' : 'hello'
The problem with ('2'||'1') is that the whole section there gets evaluated to a single expression before the comparison against a is made, and || will evaluate to the initial value if it's truthy. So ('2' || '1') resolves to '2'.
var a = 1;
a == '2'?'hi': a=='1'?'hello' :'';
i Found this is also working.... Thanks to everyone who answered using different ways..

Unable to see the correct value by using && operator [duplicate]

This question already has answers here:
Javascript AND operator within assignment
(7 answers)
Closed 7 years ago.
hi i am preparing for js interview.
i saw this question.
if var a=2, var b =3 What would be the value of a&&b?
The answer given is 3.
I am not able to understand why is this the answer.
Can you help..
Thanks.
&& and || do not create true or false. They return one of the operands.
The binary operators do NOT behave like other c based languages. See more about truthy and falsey values here
&& is defined as follows.
If the first operand is truthy then the result is the second operand. Otherwise it is the first.
Examples
false && true // false the first operand is falsey
0 && true // 0. 0 is a falsy value so the first value is used
1 && 0 // 0. The first value is truthy
// so the second value is used
'hello' && 'world' // 'world' the first value is truthy
// so yield the second value.
|| is defined as follows.
If the first operand is truthy then the result is the first operand. Otherwise it is the second.
Examples
false || true // true, first value is falsey so yield second
0 || true // true, first value is falsey so yield second
1 || 0 // 1, first value is truthy use it.
'hello' || 'world' // 'hello', first value is truthy so yield it.
&& and || are "Short-circuit"
This means that there are ways to structure code such that not all expressions are evaluated. This can be convienient at times but is double edged.
function launchNukes() { /* TODO */ }
0 && launchNukes(); // nukes do not fire
1 && launchNukes(); // nukes fire
0 || launchNukes(); // nukes fire
1 || launchNukes(); // nukes do not fire
&& is an AND operator, just like most everywhere else. Most languages, JavaScript included, will stop evaluating an AND operator if the first operand is false.
You can read it like that:
if a is true , return value will be b
if a is false , return value will be a
So && return values of operands not false and true.
for your example,
2 && 3 // return 3 because 2 is true

JS: why does this return true?

0 + 1 === 1 || 1 + 1 === 2 || 2 + 1 === 10
Can someone please explain why this statement returns true?
Individually, the first two are true and the last one is false. However OVERALL, the statement returns true. It seems that you just need one true statement among a longer list of statements to make the OVERALL statement return true. Is that correct?
Just trying to cement my understanding of Booleans. Cheers.
Well, || returns the first truthy value if there is one so:
1 || ANYTHING_IN_THE_WORLD ; // returns 1
So all you really have there is
0 + 1 === 1
Which is true. So yes, your understanding is correct.
Expanding on execution order:
Operator precedence is in play here:
0 + 1 === 1 || 1 + 1 === 2 || 2 + 1 === 10
First we have addition:
1 === 1 || 2 === 2 || 3 === 10
Then we have equality checks:
true || true || false;
Which as explained above true || ANYTHING_AT_ALL is true, so the final output is true.
|| is an or operator. So if condition one or condition two or condition 3 is true, the statement is true.
I suggest reading up on JavaScript here: https://developer.mozilla.org/en/docs/Web/JavaScript
it returns true because with OR operator (||) first true will return true.
The evaluation will perform :
> 1- is (0+1===1)
=> true! Then returns true.
This
> 0+1===1 || 1+1000===1
will return true for the same reason.
"some apples are purple OR some apples are green" is true because it is sufficient that some apples are green. a OR b will be true when either or both are true. a AND b needs both to be true.
Thus, the fact that some of the items in your expression are true makes the whole expression true. It would not be if you replaced || with &&.
In fact,
It seems that you just need one true statement among a longer list of statements to make the OVERALL statement return true. Is that correct?
is (almost) exactly correct. The only correction I'd put in is replacing "true" with "truthy", at least in the context of JavaScript. For example, 3 || 5 is not true, but 3 - while 3 is not true, it is truthy.

Variable assignment inside an 'if' condition in JavaScript

How does the below code execute?
if(a=2 && (b=8))
{
console.log(a)
}
OUTPUT
a=8
It has nothing to do with the if statement, but:
if(a=2 && (b=8))
Here the last one, (b=8), actually returns 8 as assigning always returns the assigned value, so it's the same as writing
a = 2 && 8;
And 2 && 8 returns 8, as 2 is truthy, so it's the same as writing a = 8.
It's generally a bad idea to do variable assignment inside of an if statement like that. However, in this particular case you're essentially doing this:
if(a = (2 && (b = 8)));
The (b = 8) part returns 8, so we can rewrite it as:
if(a = (2 && 8))
The && operator returns the value of the right hand side if the left hand side is considered true, so 2 && 8 returns 8, so we can rewrite again as:
if(a = 8)
It is called operator precedence
(a=2 && (b=8))
In the above example. then results are evaluated against the main && sign.
(a=2 && (b=8)) evaluated to a = 2 && 8
So 2 && 8 return a = 8
You're setting (not comparing) a to 2 && (b=8). Since 2 is tru-ish the second half of the expression will be executed, i.e. a = true && (b = 8), i.e. a = (b = 8), i.e. a = 8.
Your statement is interpreted like
a = (2 && (b=8))
when you uses && statement, then last true statement value will be returned. Here (b=8) will becomes value 8 which is true and last statement.
To understand what is going on, refer to the operator precedence and associativity chart. The expression a = 2 && (b = 8) is evaluated as follows:
&& operator is evaluated before = since it has higher priority
the left hand expression 2 is evaluated which is truthy
the right hand expression b = 8 is evaluated (b becomes 8 and 8 is returned)
8 is returned
a = 8 is evaluated (a becomes 8 and 8 is returned)
Finally, the if clause is tested for 8.
Note that 2 does not play any role in this example. However, if we use some falsy value then the result will be entirely different. In that case a will contain that falsy value and b will remain untouched.

'' equals false in Javascript? What would be the safest way to distinguish between '' and boolean false?

We use an external API whcih returns '' or boolean false while Javascript seems to find the both equal.
for example:
var x = '';
if (!x) {
alert(x); // the alert box is shown - empty
}
if (x=='') {
alert(x); // the alert box is shown here too - empty
}
var z = false;
if (!z) {
alert(z); // the alert box is shown - displays 'false'
}
if (z=='') {
alert(z); // the alert box is shown here too - displays 'false'
}
How can we distinguish between the two?
Use the triple equal
if (x===false) //false as expected
if (z==='') //false as expected
A double equal will do type casting, while triple equal will not. So:
0 == "0" //true
0 === "0" //false, since the first is an int, and the second is a string
var typeX = typeof(x);
var typeZ = typeof(z);
if (typeX == 'string' && x == '')
else if (typeX == 'boolean' && !typeX)
I like Peirix's answer too, but here is an alternative.
as mentioned by peirix: tripple equal signs check both the value and the type
1 == '1' // true
1 === '1' // false
For avoid this questions use jslint validator. It helps for find unsafe operations.

Categories

Resources