JavaScript conditionals, terminate on first "true"? [duplicate] - javascript

This question already has answers here:
Does a javascript if statement with multiple conditions test all of them?
(10 answers)
Closed 5 years ago.
Does JavaScript operate the same as languages like C where if multiple conditionals are given, then the if statement when the entire thing can be guaranteed to be evaluated false/true?
I.E.
if( x == y || y == z)
or
if( x == y && y == z)
I know C doesn't check the second conditional in the first statement if the first conditional is evaluated true, as well as not checking the second conditional in the second statement is the first conditional is evaluated false.
I realize this is a quick Google, but I completely forgot what this compiler-level behavior is called and as a result was not able to find the answer.

We can run a simple javascript test to see this in action.
function check(){
console.log('called');
return true;
}
let x = true, y = true;
if(x != y || x == check()){
console.log('or verified');
}
if(x != y && x == check()){
console.log('and verified');
}
Our console doesn't display and verified for our second if statement since it never runs.

What you are looking for is short circuit evaluation. Yes, javascript short circuits so that the second expression won't be evaluated if it doesn't need to be.

Yes. It's called short-circuit evaluation!
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Short-circuit_evaluation

Yes Javascript has it and the name is "short circuit evaluation" just like C. In fact I often use this to make sure I don't read a property from a object that doesn't exist.
For example:
return object && object.property
You can read more about this here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

Related

why does the text always show "you rolled a 1" when button is clicked? [duplicate]

This question already has answers here:
IF Statement Always True
(3 answers)
Closed 5 years ago.
I have the following code:
console.log(usernameExists);
if (usernameExists = true) {
console.log("returning true");
return true;
} else if (looped = true) {
console.log(usernameExists+" is returned");
looped = null;
return false;
}
The first console.log(usernameExists) is returning false, but still I am getting a console message of "returning true", and the function in which this is, is returning true! I simply can't figure this out.
The condition is always true, because you assign this value to the variable and this is the value which is evaluated for the if clause.
But you could use a direct check without a compare value (and without assigning this value).
Beside that, you could change the else part to only an if part, becaue you exit the function with return, so no more else happen in this case.
if (usernameExists) {
console.log("returning true");
return true;
}
if (looped) {
console.log(usernameExists+" is returned");
looped = null;
return false;
}
= is an assignment, so you're setting the variable to true, which itself makes the if statement true. What you want is to check if the variable is set to true. In order to do that, use the == or === operators.
For checking conditions, you need to use '==' operator. '=' means assignment operator.
Whereas a '===' checks for value and type.
Hope that is the issue.
In your conditions you are using a single equal!!!
Therefore, it is a assignation operation that is done instead of comparison! So you are not checking that your variable is equal to true but you are assigning it to true and since your assignement operation was successful your condition is at the same time fulfilled.
Change it with two or tree equals == or === instead of =
Usage and differences between == and === are explained very well here:
Which equals operator (== vs ===) should be used in JavaScript comparisons?

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.

Call a function when two conditions are right using IF statement [duplicate]

This question already has answers here:
Logical Operators (AND Operators)
(3 answers)
What does this symbol mean in JavaScript?
(1 answer)
Closed 4 years ago.
I need to know how to look for two values in if statement.
I know about a method where the code will be executed when at least one value matches the specified number like in here:
if (x == 0 || y == 0) {
// code to be called
}
But the code above will be executed even if one value matches 0 and the other not. What's the way to check if both x and y are equal to 0?
I couldn't find the answer anywhere...
Use the AND operator instead of the OR operator, that is
if (x == 0 && y == 0) {
// code to be called
}
You want to use AND, which is &&

if(a = 1) is true [duplicate]

This question already has answers here:
Variable assignment inside an 'if' condition in JavaScript
(6 answers)
Closed 6 years ago.
I don't know if it's possible duplicate. Testing my code, sometimes I was wrong with because I put = and not == or === in if conditions:
Consider this code :
var a = 0;
if(a = 1) console.log('true');
I don't know why this is not an error and why returns true the condition (a = 1)
I guess that what it does is assign 1 to the a variable, but why this evaluates to true and there's no error?
you're setting a to 1 and then checking the truthiness of the result. Non-zero numbers in JavaScript are true, so you get what you see.
Like in math, things are evaluated left-to-right, with parens going first.
As it was said, it does assign to your variable and will return true for all values other than 0.
A way to avoid these kind of mistakes is to change the test.
if( 3 == a)
Here if you ever write (3 = a) you would have an error.

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.

Categories

Resources