returning with && - javascript

What does it mean to return a value with &&?
else if (document.defaultView && document.defaultView.getComputedStyle) {
// It uses the traditional ' text-align' style of rule writing,
// instead of textAlign
name = name.replace(/([A-Z]) /g, " -$1" );
name = name.toLowerCase();
// Get the style object and get the value of the property (if it exists)
var s = document.defaultView.getComputedStyle(elem, " ") ;
return s && s.getPropertyValue(name) ;

return a && b means "return a if a is falsy, return b if a is truthy".
It is equivalent to
if (a) return b;
else return a;

The logical AND operator, &&, works similarly. If the first object is falsy, it returns that object. If it is truthy, it returns the second object. (from https://www.nfriedly.com/techblog/2009/07/advanced-javascript-operators-and-truthy-falsy/).
Interesting stuff!
EDIT:
So, in your case, if document.defaultView.getComputedStyle(elem, " ") does not return a meaningful ("truthy") value, that value is returned. Otherwise, it returns s.getPropertyValue(name).

The AND && operator does the following:
Evaluate operands from left to right.
For each operand, convert it to a boolean. If the result is false, stop and return the original value of that result.
If all other operands have been assessed (i.e. all were truthy), return the last operand.
As I said, each operand is convert to a boolean, if it's 0 it's falsy and every other value different than 0 (1, 56, -2, etc etc) are truthy
In other words, AND returns the first falsy value or the last value if none were found.
// if the first operand is truthy,
// AND returns the second operand:
return 1 && 0 // 0
return 1 && 5 // 5
// if the first operand is falsy,
// AND returns it. The second operand is ignored
return null && 5 // null
return 0 && "no matter what" // 0
We can also pass several values in a row. See how the first falsy one is returned:
return 1 && 2 && null && 3 // null
When all values are truthy, the last value is returned:
return 1 && 2 && 3 // 3, the last one
You can learn more about the logical operator here https://javascript.info/logical-operators

Related

Javascript short circuiting in if statement

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.

Explanation for why this condition '' && false would return ''

I am a bit confused with this condition:
console.log('' && false) //''
I was expecting it to return false, however it returns ''
but with empty space, it's returning false
console.log(' ' && false) //true
Could someone please explain the reason for this?
My answer was found here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
Returns expr1 if it can be converted to false; otherwise, returns
expr2. Thus, when used with Boolean values, && returns true if both
operands are true; otherwise, returns false.
So console.log('' && false) //''
because '' can be converted to false (!!'' will return false), it will return ''
What you are receiving out of the first log, '' is not the same condition string. Check this:
console.log('' && false || 'else string')
And you will see it logs the 'else string'. Since your condition has zero length, it goes after the else which does not exist. So it simply shows an emoty string.
Zero length strings are falsy in general and that's why you get false result out of the second one.
"&&" operator evaluates the first operand and proceeds to next operand only if first operand is evaluated to some truthy value or true itself. This evaluation continues until the complete expression is evaluated.
For example, a==b && b>=7 && c==6. In this, only if a==b is true it checks b>=7 and if this evaluates to true then it checks c==6.
Here in your question, '' is an empty string and is a falsy value. Hence, it didn't proceed for the last operand and returned ''. For more information on truthy and falsy values in javascript go through this link: https://www.sitepoint.com/javascript-truthy-falsy/

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

Javascript Optimal way of checking false statement except zero

In javascript we use shortand notation if(input){} to check for empty or null input. We will get false for Null, Undefined, false, 0, NAN, "". My requirements is that I want to get true for any number including zero so I have created a method as follows
function checkFalseExceptZero(value){
if( value !== undefined && value !== null && value !== false && value !== "" && value.length !== 0 ) return true;
else return false;
}
I have added all possible checks in the above method to get the desired result. I am curious if there is any quick, sweet, short or more robust approach to achieve the same?
A simple to understand answer. The three equal signs in JS will not convert type to check if the values equal unlike the two equal signs.
0 == false //true
0 === false //false, because 0 is a number and false is a boolean
Therefore, the answer, if you want to put it inside a function:
JS:
function isNumber(v) {
return typeof v === "number"
}
The function will check the type of the variable. So it is not actually comparing the value to determine the result. The function will only return true if the type of the variable is called number.
Test runs:
isNumber(0) //true
isNumber(false) //false
isNumber("0") //false
isNumber(undefined) //false
In case you want to know, typeof variable will return a string.
My requirements is that I want to get true for any number including
zero so I have created a method as follows
function checkFalseExceptZero(value){
if ( variable.constructor === Array) return !!value.length;
return value === 0 || !!value;
}
This a shorter version of your function. This returns true only when value is 0 or a trully value.
So :
checkFalseExceptZero(null) ==> false;
checkFalseExceptZero(undefined) ==> false;
checkFalseExceptZero(false) ==> false;
checkFalseExceptZero("") ==> false;
checkFalseExceptZero(0) ==> true;
checkFalseExceptZero([]) ==> false;
checkFalseExcpetZero([1]) ==> true;
For any valid number, including 0, JavaScript already exposes the isFinite function. This returns false for all non-numbers, as well as for infinite and NaN
Examples (excerpt from the linked mdn page):
isFinite(Infinity); // false
isFinite(NaN); // false
isFinite(-Infinity); // false
isFinite(0); // true
isFinite(2e64); // true
isFinite("0"); // true, would've been false with the
// more robust Number.isFinite("0")

Categories

Resources