Why ternary expression is executed after falsy value in Javascript? - javascript

As far as I know expressions are not executed after falsy values in Javascript. For example in the following statement:
const result = undefined && 5;
console.log(result);
result will be undefined.
However:
const result = false && false ? 'T' : 'F';
console.log(result);
result will be equal to F. Why is the ternary expression still executed?

This is because of operator precedence: && has higher precedence (6) than ? : (4), so
false && false ? 'T' : 'F'
evaluates to
(false && false) ? 'T' : 'F'
So, the left-hand side evaluates to false first (taking the first false), and then goes on to the conditional operator.
If you had put parentheses after the &&, result would be false, as you're expecting:
const result = false && (false ? 'T' : 'F');
console.log(result);

const result = false && false ? 'T' : 'F'
As we know ternary expression is a short form of IF else condition,the above statement is like
if(false && false){
return 'T'
}else{
return 'F'
}
So result value we getting as "F"

Related

Why does this short circuit evaluation return undefined if first value is false?

I have an example similar to this where the first expression evaluates to false and the second is undefined but the overall expression returns undefined into valueResult, shouldn't the first false value terminate the check and return false?
valueResult = false && 10 === 5 ? 'match' : undefined
I have added console log statements and a debugger and this is what is happening, however when I do false && undefined on the browser console, it returns false.
In your updated example, the logical AND … && … has a higher order of precedence (5) than the evaluation of the ternary … ? … : … (3).
Check out the table on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#table
&&-operator has higher precedence then the ternary operator. That's why following is happening:
Basically you have a ternary operator (false && (10 === 5) ? : 'match' : undefined. 10 === 5 evaluates to false and false && false also results in false. Thats why undefined and not 'match' is returned.
To fix this, add parentheses after && like this:
false && (10 === 5 ? 'match' : undefined)

Why my condition is always true

I would like to know in this example why my condition is always true ? Thanks
function bla() {
var qix = 'z'
if (qix === 'a' || 'b' || 'c') {
console.log('condition ok!! whats wrong???')
}
}
The problem with your code is that the if expression always evaluates to true.
qix === 'a' || 'b' || 'c'
will actually become this:
false || 'b' || 'c'
as qix is set to z. Due to loose typing, JavaScript returns true for the second expression because 'b' is a truthy value. To correct that, you need to change the expression as follows:
qix === 'a' || qix === 'b' || qix === 'c'
so that it correctly means what you're expecting.
Description of expr1 || expr2 from MDN:
Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true.
o1 = true || true // t || t returns true
o2 = false || true // f || t returns true
o3 = true || false // t || f returns true
o4 = false || (3 == 4) // f || f returns false
o5 = 'Cat' || 'Dog' // t || t returns "Cat"
o6 = false || 'Cat' // f || t returns "Cat"
o7 = 'Cat' || false // t || f returns "Cat"
o8 = '' || false // f || f returns false
o9 = false || '' // f || f returns ""
So this expression from your code, assuming qix is not 'a':
qix === 'a' || 'b' || 'c'
The first term qux === 'a' is false, which of course evaluates to false. This causes it to go to the next term which is 'b'. Non-empty strings evaluate to true, so it stops there and just becomes 'b'. Now your if statement can be thought of as just:
if ('b')
Again, 'b' evaluates to true. So your conditional is effectively doing nothing.
I think you are missing two concepts.
First how the || operator works and second coercion of javascript values.
In your code:
if ('z' === 'a' || 'b' || 'c') { ----}
Will always evaluate to true.
The reason for this is that the || operator will give back the first value which coerces to true without actually coercing the value. The associativity (order which the operators are executed) is left-to-right. This means that the following happens:
First the following will be evaluated because it has higher precedence:
'z' === 'a' // false
then we have the following expression which will be evaluated left to right:
false || 'b' || 'c'
let foo = false || 'b'
console.log(foo)
Then we have the following expression:
let foo = 'b' || 'c'
console.log(foo)
So the whole expression evulates to the string 'b'
After the expression inside the if statement is evaluated to the value 'b' this in turn then gets coerced into a boolean. Every string gets converted to true and that's why the value is always true.
This is because you 'if condition' is take 3 possible option
First say qix === 'a', this is false but you asking about 'b','c' and this option are values true because you are not compare var qix with 'b' or 'c', you only asking to IF condition, that if 'b' or 'c' are value
the operator || it is used so
if(First Condition || Second Condition || third condition){
if at least one of these options is true, then enter here
}
In ECMAScript 2016 incorporates an includes() method for arrays that specifically solves the answer
if (['b', 'c', 'a'].includes(qix)) {
this is false
}
if (['z', 'c', 'a'].includes(qix)) {
this is true
}
Or you can write so
function bla() {
var qix = 'z'
if (qix === 'a' || qix === 'b' || qix === 'c') {
console.log('condition ok!! whats wrong???')
}
}
As we know || (OR Logical Operators) returns true if either operand is true. In your if condition qix === 'a' || 'b' || 'c' in their second and third operand is string and Strings are considered false if and only if they are empty otherwise true. For this reason, your condition is always true.
Need to check qix like qix ==='b'
var qix = 'z'
if (qix === 'a' || qix === 'b' || qix ==='c') {
console.log('condition ok!! whats wrong???')
}
else{
console.log('else')
}
You could use Regex: qix.match(/^(a|b|c)$/)
Should return if qix is equals to a or b or c
var qix = 'z';
if (qix.match(/^(a|b|c)$/)) {
console.log('condition ok!! whats wrong???');
} else {
console.log('else');
}
JavaScript returns true for the second or expression because 'b' is always true.
You need to check each value against qix like so:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators
var qix = 'z'
if (qix === 'a' || qix === 'b' || qix === 'c') {
console.log('condition ok!! whats wrong???')
}

Why '=' and '||' will be evaluated to be true?

I read this post, it mentioned this if (variable == 1 || 2 || 6) cannot work (JS Short for if (a == b || a == c)).
But I tried this example, it will be evalauted to be true, why?
var a = 'apple';
if('apple2' == a || 'banana' ) {
alert('hi');
}
Here is the working example:
https://jsfiddle.net/Loun1ggj/
Update:
if('apple2' == a || 'banana' ) is not evaluated into if('apple2 == a' || 'apple' == 'banana')?
Let's break down the expression:
if('apple2' == a || 'banana' )
The first part to be evaluated is the ==, because it has highest operator precedence:
'apple2' == a
This is a standard equality, and returns false, giving us:
if(false || 'banana')
The || operator in JS returns not true or false, but whichever of its arguments is "truthy". A non-empty string like 'banana' is considered "truthy", so we end up with this:
if('banana')
Now we again look at the "truthiness" of 'banana', and the if statement proceeds.
Since 'banana' is always true, it would always run, see the below example
var a = 'apple';
if('apple2' == a) {
alert('hi');
}
if('banana'){
alert('hello');
}
if('apple2' == a || 'banana' ) is evaluated this way:
if(('apple2' == a) || ('banana') ), which is:
if :
'apple2' == a // false
||(or)
'banana' // true, since Boolean('banana') is true (a non-empty string is a truthy value)
so => if (false or 'banana') => if ('banana') // => true
It's not evaluated as if('apple2' == a || 'apple2' == 'banana' ).
According to this, the operator == has higher precedence over operator ||. So the expression is evaluated as follows:
if('apple2' == a || 'banana' )
'apple2' == a //false
'banana' //true (non-empty string)
So final evaluation will be, always true:
if(false || true) //true
There's 2 expressions here
'apple2' == a which resolve to falsy
'banana' which resolve to thruthy
Because 'banana' is not undefined or null essentially.

|| converting empty string to bool, && not

Is this normal? Is it a feature or a bug? (I'm using firebug):
>>> '' || true
true
>>> '' || false
false
>>> '' && false
""
>>> '' && true
""
It is not converting the empty string to Boolean.
With ||
It is evaluating the left hand side, of which an empty string is falsy. It then checks the right hand side (because it's an or, and that side may be true), and returns that value.
With &&
Because && needs both sides to be true and the left hand side is falsy, it doesn't bother checking the right hand side (short circuit evaluation). Therefore, it just returns the left hand side, which is the empty string.
JavaScript always returns the last value it evaluated.
>>> '' || 0 || undefined || null || false || NaN || 'hello'
"hello"
It's not that one is converting and the other isn't; the lines with || are returning their second operand and the lines with && are returning their first, due to short-circuiting.
[ECMA-262 11.11]: Semantics
The production LogicalANDExpression : LogicalANDExpression &&
BitwiseORExpression is evaluated as follows:
Let lref be the result of evaluating LogicalANDExpression.
Let lval be GetValue(lref).
If ToBoolean(lval) is false, return lval.
Let rref be the result of evaluating BitwiseORExpression.
Return GetValue(rref).
The production LogicalORExpression : LogicalORExpression ||
LogicalANDExpression is evaluated as follows:
Let lref be the result of evaluating LogicalORExpression.
Let lval be GetValue(lref).
If ToBoolean(lval) is true, return lval.
Let rref be the result of evaluating LogicalANDExpression.
Return GetValue(rref).
The LogicalANDExpressionNoIn and LogicalORExpressionNoIn
productions are evaluated in the same manner as the
LogicalANDExpression and LogicalORExpression productions except
that the contained LogicalANDExpressionNoIn,
BitwiseORExpressionNoIn and LogicalORExpressionNoIn are evaluated
instead of the contained LogicalANDExpression, BitwiseORExpression
and LogicalORExpression, respectively.
NOTE The value produced by a && or || operator is not necessarily
of type Boolean. The value produced will always be the value of one of
the two operand expressions.
The || operator will return the first value which is truthy.
The && operator will return the second value if the first is truthy, otherwise it returns the first.
For more info, you can see the Logical Operators page on the MDC site.
In your case,
'' || true; '' is false, so the || operator moves onto the second value, which is true, and so returns it.
'' || false; '' is false, so the || operator moves onto the second value, which is false, and has no more values to compare, so returns it.
'' && false; the first value ('') is falsy, so it returns it.
'' && true; the first value ('') is falsy, so it returns it.

Javascript Logical Operator:?

I was examining the src of underscore.js and discovered this:
_.isRegExp = function(obj) {
return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
};
Why was "!!" used? Should it be read as NOT-NOT or is there some esoteric JS nuance going on here?
It is just an obtuse way to cast the result to a boolean.
Yes, it's NOT-NOT. It is commonly used idiom to convert a value to a boolean of equivalent truthiness.
JavaScript understands 0.0, '', null, undefined and false as falsy, and any other value (including, obviously, true) as truthy. This idiom converts all the former ones into boolean false, and all the latter ones into boolean true.
In this particular case,
a && b
will return b if both a and b are truthy;
!!(a && b)
will return true if both a and b are truthy.
The && operator returns either false or the last value in the expression:
("a" && "b") == "b"
The || operator returns the first value that evaluates to true
("a" || "b") == "a"
The ! operator returns a boolean
!"a" == false
So if you want to convert a variable to a boolean you can use !!
var myVar = "a"
!!myVar == true
myVar = undefined
!!myVar == false
etc.
It is just two ! operators next to each other. But a double-negation is pointless unless you are using !! like an operator to convert to Boolean type.
It will convert anything to true or false...

Categories

Resources