JavaScript - type conversion [duplicate] - javascript

This question already has answers here:
what does && return in javascript expression
(4 answers)
Closed 3 years ago.
> "s" && true;
true
> true && "s";
's'
I thought these two expressions would return same values.
Why not? How does it work?

See MDN:
expr1 && expr2: If expr1 can be converted to true, returns expr2; else, returns expr1.
&& evaluates to the value of the last truthy expression, so if both operands are truthy, the whole thing will evaluate to the first operand.
If the first operand is falsey, it'll evaluate to the (falsey) value of the first operand.
Similar to ||, you can think of it as evaluating to the value of the expression that determines the final value. (If evaluating the left operand provides a truthy result with ||, there's no need to evaluate the right - similarly, if the right operand produces a falsey result with &&, there's no need to evaluate the left.)

Related

Javascript OR Expression: return Operand that is *not* NaN

I have an OR expression that should return the operand that is anything else than NaN:
(1 || NaN) // evaluates to 1
(NaN || 1) // evaluates to 1
But when the other operand is also a falsy value like 0, null, undefined or false, Javascript returns always the rightmost operand:
(0 || NaN) // evaluates to NaN
(NaN || 0) // evaluates to 0
// same for combinations of 0, null, undefined and false
Is there a way to fit the desired behaviour "Return the operand that is not NaN" into a nice & short expression or do I have to rely on an if/else construct?
You could add a default falsy value at the end of the expression, like
result = yourValue0 || yourValue1 || 0;
In this case, you get either a truthy value of yourValueX or the last falsy value.
Use an if-else-expression, also known as the conditional operator:
!isNaN(a) ? a : b
Try this:
var notNaN = [value1, value2, value3].find(item => !Number.isNaN(item))
This kind of operators use a lazy mechanism for their computation and this concept is called short circuting in javascript. Basically, JS returns value as soon as it feels no more computation is required to evaluate this expression. So, if its an && operator it will return as soon as it finds first non-truthy(0, "", null, undefined, NaN) as for && operator if any of the operands is non-truthy there is no point check rest of the operands as expression is already non-truthy, so it returns that value and exits, now if all the operands are truthy it checks till last and returns the last value. For || its just the opposite as soon as it finds first truthy value it returns otherwise keeps checking till last and returns it.

JavaScript Syntax: actual = node.nodeType === 1 && node.getAttribute(att) [duplicate]

I don't understand how &&, ||, and ! work... both with bools and other data types. How do you use them?
All values in JavaScript are either “truthy” or “falsy”.
a && b evaluates to the first falsy operand,
a || b evaluates to the first truthy operand.
Both operators will not evaluate any operands after the one the return.
If all operands don’t match, they will evaluate to the last one.
!a evaluates to true if a is falsy and false if a is truthy.
All values are truthy except the following, which are falsy:
null
undefined
false
+0
-0
NaN
0n
""
document.all
If you want to test that both of two conditions are truthy then use &&:
if (isX && isY)
{
// Do something.
}
If you want to test that one or both of two conditions are truthy then use ||:
if (isX || isY)
{
// Do something.
}
The ! inverts a boolean (a truthy value becomes false and vice versa).

What is the meaning of || in javascript?

I am looking at these lines of code from here:
if (callback)
callback(sig || graph);
I have never see vertical "or" bars in a javascript method call. What do they mean? Do they pass the "true" parameter (i.e. sig or graph)? Do they pass the defined parameter? I have never seen that syntax before.
This is the logical OR operator in JS (and most other languages). It is defined in the spec at 11.11. As noted in the spec, expressions on either side will be evaluated first and the logical OR is left-to-right associative. Note that evaluation of the operands follows standard ToBoolean semantics from section 9.2, so [null, undefined, 0, ''] all count as falsy.
Unlike most languages, JS returns the left operand if it is truthy or the right operand otherwise. This behavior has been covered before in a number of SO questions, but is worth noting as most languages simply return true or false. This behavior is often used to provide default values to otherwise undefined variables.
The Logical OR operator (||) is an operator that returns its first or second operand depending on whether the first is truthy. A "truthy" value means anything other than 0, undefined, null, "", or false.
This operator uses short-circuiting, meaning if the first expression is truthy, then the second expression is not evaluated and the first operand is returned immediately. This is akin to the Logical AND operator (&&), which does the opposite: if the first operand is falsey, it returns it, otherwise it returns the second expression.
It means 'or' (http://www.w3schools.com/js/js_comparisons.asp) So if(sig OR graph)
BE CAREFUL you can 'short circuit' your code using this.
example :
If (foo || foo2)
if foo is true, then JavaScript wont even test foo2 at all, it just skips it.
It passes whichever evaluates as true, or sig if both are true.
The double pipe (||) represents OR in JS. In simple words, either this or that is True. It requires any of the sides true to get a True result.
For example:
var x = 8;
var y = 'c';
x >= 8 || y === 'a'
The left side of the double pipe returns True where the right side is False. Thus, the result is True.
The operator || means OR.
If either sig or graph are true or not null variables, callback function will receive a true argument.

In JavaScript, why does (undefined && true) return undefined? [duplicate]

This question already has answers here:
Javascript AND operator within assignment
(7 answers)
Closed 8 years ago.
Using the node.js console (node 0.10.24)
> var x = (undefined && true);
undefined
> x;
undefined
> x = (true && undefined);
undefined
> x;
undefined
Why does the comparison return undefined? I would expect it to return false since undefined is considered "falsey".
The && operator proceeds by internally coercing the values of the expressions to boolean, but the result of the operator is always the actual, uncoerced value of the first expression that failed (i.e., that was falsey).
Thus (true && undefined) will result in undefined because true is not falsey. Similarly, (true && 0) would evaluate to 0.
In javascript || and && are not guaranteed to return boolean values, and will only do so when the operands are booleans.
a = b || c is essentially a shortcut for:
a = b ? b : c;
a = b && c is essentially a shortcut for:
a = b ? c : b;
//or
a = !b ? b : c;
To formalize what others are saying, here's what the ECMAScript specification says about how the logical AND operator is evaluated:
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).
And perhaps most relevant, the note at the bottom of section 11.11:
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 other answers are more than adequate, I'm including my answer here for posterity just in case someone else's brain works like mine:
The result of the boolean || and boolean && operators will always be the result of the last expression evaluated, taking into consideration short circuiting.
So, for ||, if the first expression is truthy, short circuit evaluation means that the rest is ignored, and the result will be the value of that first expression. If it's falsy, evaluation must continue to the second expression, and the result will be the result of that second expression no matter whether it's truthy or falsy.
Likewise for &&, if the first expression is falsy then evaluation stops and the result is the result of that first expression, if it's truthy then evaluation continues and the result is the result of the second expression.

Retrieve the result of an OR logic operation in JS

A logical statement always returns a boolean value, true or false.
But how do you retrieve the true statement in a OR logical operation?
In JavaScript, the OR and AND operators always return one of their operands. The OR operator returns the first falsy operand (and doesn't evaluate any operands after that) or the last operand if they are all truthy. The AND operator similarly returns the first truthy operand or the last operand if they are all falsy.
If you wish the result to be a boolean, you can use the ! operator which returns true for falsy values and false for truthy values.
To sum it up:
!!(a || b) will return true if a and/or b are truthy and false otherwise.
a || b will return a if a is truthy and b otherwise.
EDIT:
After some explanations it seems that what you are looking for is separating the evaluation of the OR.
if (a === 56) {
// a is what you are looking for
} else if (b === 56) {
// b is what you are looking for
} else {
// neither a nor b are what you are looking for
}
The above piece of code does the exact same evaluations as your code but you have a branch of code that executes when the first expression is true and another branch which executes if the first expression is false and the second expression is true.

Categories