Precedence If Clause Parenthesis and Equality [duplicate] - javascript

This question already has answers here:
Which Logic Operator Takes Precedence
(6 answers)
The order of operators in JavaScript (|| ,&&)
(4 answers)
Closed 3 years ago.
Parenthesis have higher precedence than equality.
So from my understanding, the higher precedence is evaluated first.
Lets now assume I compare a which is not defined:
if (a == 1) { .. // throws an exception because a is not defined
Actual case:
if (typeof a !== 'undefined' && (a == 1)) {
console.log(1)
} else {
console.log(2)
}
should be evaluated in this order:
(typeof a !== 'undefined' && (a == 1))
(a == 1)
typeof a
result from (3) !== 'undefined'
"result from (4)" && "result from (2)"
But this would usually throw an exception if a is not defined but it doesn't.
Why is the left side of the equation evaluated first even though it has the lower precedence?
EDIT: I adapted the example from '||' to && just because || would always throw.

|| is evaluated left-to-right:
5 Logical OR left-to-right … || …
So the inner expression that gets evaluated first is typeof a, as part of typeof a !== 'undefined'.
If the right-hand side of the || contains more expressions nested in parentheses, regardless of their operator precedence, they will only be evaluated after the left-hand side of the || has been evaluated.

Related

Understanding JavaScript evaluation [duplicate]

This question already has answers here:
Operator precedence with JavaScript's ternary operator
(7 answers)
Closed 3 years ago.
I am fixing some code and trying to understand a certain evaluation that is happening. There was a little snippet written where 2 evaluations should happen like so :
const active = true;
const isPerson = true;
const person1Time = null;
const person2Time = null;
// this one is not working as intended
const original = !active && isPerson ? !person1Time : !person2Time;
console.log("original", original);
// fixed when second evaluation is wrapped in parens
const fix = !active && (isPerson ? !person1Time : !person2Time);
console.log("fixed", fix);
I was able to fix the code to the desired result by wrapping the ternary evaluation in parentheses. What I am wondering is - why it works like this? The !active evaluates to false, and the ternary evaluates to true, and a console.log(true && false), this evaluates to false. Perhaps I am misunderstanding something here.
Boolean operators take precedence over ternary operators. In other words, this:
!active && isPerson ? !person1Time : !person2Time;
is equivalent to this:
(!active && isPerson) ? !person1Time : !person2Time;
Therefore, you obtain a different result.
Follow the operator precedence rules:
Binary AND (x && y) is priority 6.
Ternary (x ? y : z) is priority 4.
Unary NOT (!x) is priority 17.
Therfore, the NOT operator is evaluated first, then the binary AND, and lastly the ternary operator.
The original is evaluating the entire conditional expression on the left side of the ternary operator: !active && isPerson. Then based on the result of that expression - true or false - it evaluates the correct result.

Why does `(state == 1 && 3)` make sense? [duplicate]

This question already has answers here:
Why the result of bool(true) && string is string in javascript?
(4 answers)
Closed 8 years ago.
I came across this code in Mithril.js:
finish(state == 1 && 3)
To my (Java/C programmer's) eyes it looks like it should always invoke finish(true) if state is 1 and finish(false) if state is not 1. But it actually seems to do finish(3) for the former and finish(false) for the latter.
What is the logic behind this?
Is this idiomatic in JavaScript, or is it a bad idea? To me it's horribly obscure.
You can interpret the operators || and && like this:
A || B
→ A ? A : B
A && B
→ A ? B : A
But without evaluating A twice.
It is a characteristic of JavaScript, && and || operators always return the last value it evaluated.
In JavaScript, the && operator doesn't force the result to a boolean. It's instead similar to:
var _temp = state == 1;
finish(_temp ? 3 : _temp);
Testing the truthiness of the left side, then returning either the right when truthy or the left otherwise.
The comparison a && b actually returns the value the last value evaluated in the expression and not true or false.
You can refer to the spec:
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).

Coffeescript existential operator sometimes checks against undefined, but not always [duplicate]

This question already has an answer here:
How does CoffeeScript's existential operator work?
(1 answer)
Closed 8 years ago.
This coffeescript...
if x? isnt '' then console.log x
Compiles to this javascript...
if ((typeof x !== "undefined" && x !== null) !== '') {
console.log(x);
}
Where typeof x is checked against undefined
However, if I use x in the current scope, coffeescript explicitly declares it at the to of the scope, and then does not bother checking for undefined...
This coffeescript...
x = y.z
if x? isnt '' then console.log x
Compiles to this javascript...
var x;
x = y.z;
if ((x != null) !== '') {
console.log(x);
}
It is possible that x ends up being undefined if y.z is undefined. Why does coffeescript not feel the need to check for undefined in the if statement?
Let's start with the more obvious case, the second example:
The compiler knows that var x is declared, even if it is not defined, so all it needs to do is check that the value isn't null or undefined which can be done with x != null.
However, this isn't the case in the first example. x hasn't been declared anywhere, so trying x != null would actually throw a ReferenceError, however typeof x will return a value (and if x is in fact not null or undefined all will be will in the universe.

javascript, strange comparison operator [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript === vs == : Does it matter which “equal” operator I use?
I've met "!==" strange comparison operator in source code of some chrome extension. Code snippet:
function closedTab(id) {
if (openedTabs[id] !== undefined) {
openedTabs[id].time = timeNow(0);
closedTabs.unshift(openedTabs[id]);
}
}
This operator is not used just once, so there's should some meaning.
Is "!==" came from some JavaScript magic? Or it's just equivalent to usual "!="?
Thanks
The difference is that !== doesn't try to convert its operands to the same type before comparing. Same with === and ==.
See this question: Difference between == and === in JavaScript
!== is the not identity comparison operator.
!= will coerce the two types to match
!== will not coerce the two types
For a few examples:
3 == "3" // true - the operands are coerced to the same type, then compared and they match
3 === "3" // false - the operands are not coerced to the same type, so do not match
3 != "3" // false
3 !== "3" // true
This is called a strict comparison operator where it not only checks for value but also for type.
The difference comes from what happens when values are of different type.
The !== operator (and its cousin ===) checks on the equality of both value and type. != and == on the other hand try to coerce values to be the same before checking equality.
For example:
if(5 === "5") // evaluates to false
if(5 == "5") // evaluates to true
The same concept is extended to != and !==
It's an identical comparison operator. It compares value and type. For example:
if('foobar' == true) // true
if('foobar' === true) // false

When should you use === vs ==, !== vs !=, etc.. in javascript? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Javascript === vs == : Does it matter which “equal” operator I use?
What are the differences between === vs == and !== vs !=?
When should you use each one?
=== is the Identity operator, and is used to test that value and type are equal.
so..
"3" == 3 // true
"3" === 3 // false
1 == true // true
1 === true // false
"1" == true // true
"1" === true // false
so when you care that value and type are equal, or not equal use Identity operators === or !==
The "normal" == operators in javascript perform type coercion, and try their best to do things like treat a string as number or an object as a string where required. The longer === operators will not do type coercion, but rather a strict comparison within the type.
=== and !== are the same as == and !=, but additionally do checks for the variable types.

Categories

Resources