Javascript short circuiting in if statement - javascript

I am confused about the below if statement code. Not sure what it is exactly doing
if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}
Can someone please help me to understand this?
Is it a short-circuiting in if statement:
i.e
1- if first this.props.filterURL from left side is false then it will return false. 2- if first this.props.filterURL has a value then it will return true and the second variable nextProps.filterURL will be compared to this.props.filterURL on the right most of the statement?

Notes :
This short-circuiting is good for the performance, as it allows significant bits of calculations to be skipped.
The AND operator (&&) returns true if both expressions are true, otherwise it returns false.
DEMO
var x = 1;
var y = 5;
if (x > 0 && y < 6) { console.log(x) }; // true
if(x > 1 && y < 6) { console.log(x) }; // false
As suggested by nnnnnn in his comment, the first this.props.filterURL is checking for a truthy value, not for true specifically. If the property is not defined that is falsy, but if the value is null or 0 or an empty string those are all falsy too.

In case of AND operator it evaluates the second expression only if the first one is true.
In your case,
if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}
can be interpreted as if(expr1 && expr2)
where expr1= this.props.filterURL and expr2 = nextProps.filterURL !== this.props.filterURL
for first expression expr1 it evaluates whether it is not null or undefined...
for the second expression expr2 nextProps.filterURL !== this.props.filterURL it checks both the value and data type. So for example if you have both value as same 1234 but for one it is of type String and for another it is for number, this condition would be true.

Related

Why does the if - block >>>> if(!variable) <<<<< get executed when variable = 0?

When I run this code the code in the if- block gets executed. My assumption was that if ! something, it's either null or undefinded? Can anyone explain?
const num = 0;
if (!num) {
console.log('Why on earth does this get printed');
}
Your assumption is incorrect. When you implicitly convert a value to a boolean like that, it's converted according to the truthy and falsy rules. The falsy values are 0, "", NaN, null, undefined, and of course, false. (Also, interestingly, document.all on browsers.) All other values are truthy. So if (!num) will be true if num is 0, because you've negated a falsy value (making it true).
If you just want to check for null and undefined, you can use == undefined or num == null (note: ==, not ===), which is true for both of them:
if (num == null) {
console.log("num is null or undefined");
}
The rules for == are such that both null and undefined are == undefined (and also == null), but nothing else is.
Or, perhaps more clearly:
if (num === null || num === undefined)
console.log("num is null or undefined");
}
When you are using if statement, code in curly braces executes only if expression in round braces return true.
You variable num has 0 assigned to it.
Variable num would be converted to false because 0 is assigned to it
In Javascript, the exclamation mark (“!”) symbol, called a “bang,” is the logical “not” operator. Placed in front of a boolean value it will reverse the value, returning the opposite.
Because of that you will get true inside curly braces
This is a reason why your code executes

OR operator with real numbers

Why is the mid number result of this statement?
(0 || 0.571428571428571 || 1) == 0.571428571428571
How the comparsion works?
Well. Looks like stupid question. For those who works in php where this statement has a different result could be helpfull to know that JS will return number instead bool.
|| is a short-circuiting operator. It evaluates its left-hand operand, and returns that if it's truthy, otherwise it evaluates and returns its right-hand operator. When you have a sequence of || operators, it performs this left-to-right, returning the first truthy value (or the last value if none are truthy).
In your example, 0 is falsey, so 0.571428571428571 is the first truthy value, and it's returned.
Your expression is interpreted as
((0 || 0.571428571428571) || 1)
The result of the first || is truthy, so that's the result of the overall expression. That's how || works: the result is the left-hand operand if it's truthy, or else the right-hand operand.
The answer to this lies in the fact that 0 is considered a false value while non-zero numbers are considered true.
Since || and && will short circuit and return as soon as it knows the outcome. For OR expressions this means that the first truthy value will be returned. For AND expressions it means the first false value is returned:
(true && true && 0 && true) === 0
(false && false && 1) === 1
(false || false || 1 || false) === 1
(false || false || 0) === 0
Since the first value in your expression is a falsey value, it is not returned but the floating point is a truthy value, so it is returned.

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

Why `int(0) and boolean` returns `int(0)` instead `boolean(false)`?

Specifically (I don't know if it can happen in others case), when I do int(0) && boolean with myString.length && myString === "true" when myString = "", it returns 0 instead of returns a boolean.
alert((function() {
var myString = "";
return myString.length && myString === "true";
})());
I know that I can fix it by do myString.length !== 0 or casting with Boolean. But I like to understand why && don't force cast the left side to boolean.
Live example: http://jsfiddle.net/uqma4ahm/1/
The && operator in JavaScript returns the actual value of whichever one of its subexpression operands is last evaluated. In your case, when .length is 0, that expression is the last to be evaluated because 0 is "falsy".
The operator does perform a coercion to boolean of the subexpression value(s), but it only uses that result to determine how to proceed. The overall value of the && is thus not necessarily boolean; it will be boolean only when the last subexpression evaluated had a boolean result.
This JavaScript behavior is distinctly different from the behavior of the similar operator in C, C++, Java, etc.
The && operator yields the left hand value if it is false-y1 and the right-hand value otherwise. (Unlike some languages, it is not guaranteed to evaluate to true or false!)
TTL for A && B:
A B (A && B)
false-y - A
truth-y - B
To make sure that only true or false is returned, it is easy to apply (double) negation:
return !!(myString.length && myString === "true")
or, equivalently
return !(!myString.length || myString !== "true")
Here is the negation TTL which leads to deriving !!(false-y) => false and !!(truth-y) => true.
A !A !(!A)
false-y true false
truth-y false true
1 In JavaScript the false-y values are false 0, "", null, undefined, NaN. While everything else is truth-y.

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