3 ways to say if:else, but which one? - javascript

In an interesting blog post, I read that there are three ways to write an if:else statement:
//method 1 - regular
if(boolean) {true condition} else {false condition}
//method 2 - shorthand
boolean ? (true condition) : (false condition)
//method 3 - logical operators
boolean && (true condition) || (false condition)
//eg: var c = r==0 && "small" || "big";
EDIT: third method IS an if:else statement, when the first part of it becomes true, the whole statement turns to true||(false condition). all modern compilers ignore the false condition then.
Now I have two questions here:
Which one of them is the most optimized? (from performance view, if any of them differs from the other, please explain why)
Is there any more methods to write an if:else statement?

Don't worry about the performance of these statements unless you are planning on running them a few thousand times per second.
If you are going to run them that often, test it yourself, you'll probably find different results under different browsers.

Related

JS Operator precedent logical and comparison

I know this has been asked a million times. But I can't find one that answers my questions directly. Just similar kinds of questions.
So this statement.
1 == !""
According to MDN operator precedent: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
Logical NOT has a higher precedent than equality.
It also mentions, assignment operators are right-associativity. Thus everything else must be left-associativity.
So on that statement. I'd of thought it would run as
!"" (coerce to a bool value, flip the value)
1 == true (compare the value)
But based on reading further down and the associativity mentions. It should run from left-to-right. Right? Which end up being the same thing, but it checks
1 ==
... then does the type coerce stuff
is my thinking right? Just wanted to make sure.

Usage of !false in a do-while loop

I saw a do-while loop that looked something like
var guess = false;
do {
stuff stuff stufff
if ( things === things){
guess = true;
}
} while ( ! guess )
This confused me because the ! operator changes the boolean value to the opposite, so that guess becomes true instead of false. So "while not false" the do-while keeps running? Or does this mean "while true" it keeps running or...?
thanks for the help!
while(!guess) means "while guess is not true".
It also can be written as while(guess == false). Maybe that way is easier to understand, although it is not a good practice.
There are some examples here: MDN - Logical operators
the actual format would be
if (things == things)
{
coding here......
}
the == mean is equal to.
the >= means greater than or equal too.
the <= means less than or equal to.
the != means that its not equal to.
so if you change the operators this would be
if (things == things) which means things are equal to things.
if (things >= things) which means things is greater than or equal to the things.
Follow the steps and for example when you use this in speech it would look like
if (speech == "things")
{
do coding.........
}
the speech is equal to things then the code will be executed

one-liner return for "if any of these is true return false" [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
If you have a function that checks 4 conditions (let's say A, B, C and D) and that if any one of them is true the function should return false.
It works if you write it like this:
function is () {
return (
!A && !B && !C && !D
)
}
However, in this case (correct me if I'm wrong) - all of the conditions will be checked each time (while it can be enough that for example A is true to stop and return false
You can simply reverse the functionality of the function and use return (A || B || C ||D ), but what if you want it to stay like that.
i.e., what I'm looking for is a one-liner return that is equivalent to:
if (a) return false;
if (b) return false;
if (c) return false;
if (d) return false;
return true;
EDIT:
As pointed out in the answers and comments, it is wrong to assume that in the first example all of the conditions will be checked each time. Once one of them evaluates to false (which means that at least one of A,B,C,D is true, i.e. "not not-true") it will stop and return false.
You are wrong about this :
However, in this case (correct me if I'm wrong) - all of the
conditions will be checked each time (while it can be enough that for
example A is true to stop and return false
In the case of a && the expression is evaluated as falseas soon as one term is false
Here is an excerpt of MDN :
Short-circuit evaluation
As logical expressions are evaluated left to right, they are tested
for possible "short-circuit" evaluation using the following rules:
false && anything is short-circuit evaluated to false.
true ||
anything is short-circuit evaluated to true.
EDIT
As mentioned in another answers and comments you can of course rewrite your expression this way:
return !(A || B || C || D)
There still should be a short circuit evaluation so there should no signifiant performance improvement but the expression might look clearer to some. IMO it is more a matter of taste.
You're wrong about how it works. Boolean operators like && and || shortcircuit; as soon as the whole expression has a known value, they stop testing. So in the code provided, if A is true, then !A is false, and it's impossible for false && <anything> to be true, so it immediately stops testing.
Every programming language I know of uses short-circuiting in cases like these, and it's not just an efficiency hack, it's a guaranteed part of the language standard, so expressions to the right of a test know that the earlier test passed. Otherwise, in a language like C, a test like if (p && p->someattr) wouldn't be safe, because without short-circuiting, p could be NULL but it would still be dereferenced to test p->someattr.
For the record, should you need to test some huge number of values to see if any are truthy, and you have them stored as an Array, you can use .some() to check them. For example:
var resultarray = ...;
if (resultarray.some(Boolean)) {
}
Or to simulate your case, where you're testing for all of them to be falsy:
var resultarray = ...;
if (!resultarray.some(Boolean)) {
}
Both of these short-circuit as soon as the find a single truthy value. Similarly, Array.every can be used to test that all entries satisfy a condition, rather than at least one, and it short-circuits when at least one falsy value is found.

Optimizing conditionals/if blocks, what is preferable from a performance point of view?

I am writing a JS library, and there are two things that have been on my mind for quite some time though.
Consider an option:
var option = { bool : true } ;
Now, imagine I do either
if(option.bool)
or
if(option.bool === true)
The first case, despite knowing for sure that it's either true or false, I imagine is the equivalent of:
var tmp = options.bool;
if ( tmp !== undefined && tmp !== null && ( tmp === true || tmp ... )
That means that to try the options.bool = true it has to check both undefined and not null, before testing for true.
Therefore the latter case should be more performant. However, the latter case, takes a considerably more characters and will lead to a larger lib, if repeated many times.
But maybe my understanding is incorrect.
Right now, even if I do:
var bool = window.t ? true : false;
if ( bool === true ) // I still have to check for true to 'have the optmimal version'?
Maybe the last case can be optimized by the compiler, but when it's a global option I imagine it's different?
Please share with me your thoughts on this.
The answer is simple. It's less about coding patterns and more about logic.
In this scenario there are always 3 possibilities and you need to cater for each of them.
Ie. 1. TRUE 2. FALSE 3. undefined
If the value is undefined then do you want it to fall under the true or false clause? OR should it be catered for differently?
Another important thing to remember is that if it is undefined then it will always execute the code in the false clause. Is that what you want?
If you know that the value will always be either true or false then I suggest that you still use the syntax == true as this is more readable. Someone browsing over the code would know that you are looking for the boolean value and not testing if the field has been set.
You have to think about these 3 cases every time you have a boolean in an if statement, so there is no 1 answer for you.

Does a javascript if statement with multiple conditions test all of them?

In javascript, when using an if statement with multiple conditions to test for, does javascript test them all regardless, or will it bail before testing them all if it's already false?
For example:
a = 1
b = 2
c = 1
if (a==1 && b==1 && c==1)
Will javascript test for all 3 of those conditions or, after seeing that b does not equal 1, and is therefore false, will it exit the statement?
I ask from a performance standpoint. If, for instance, I'm testing 3 complex jQuery selectors I'd rather not have jQuery traverse the DOM 3 times if it's obvious via the first one that it's going to return FALSE. (In which case it'd make more sense to nest 3 if statements).
ADDENDUM: More of a curiosity, what is the proper term for this? I notice that many of you use the term 'short circuit'. Also, do some languages do this and others dont?
The && operator "short-circuits" - that is, if the left condition is false, it doesn't bother evaluating the right one.
Similarly, the || operator short-circuits if the left condition is true.
EDIT: Though, you shouldn't worry about performance until you've benchmarked and determined that it's a problem. Premature micro-optimization is the bane of maintainability.
From a performance standpoint, this is not a micro-optimization.
If we have 3 Boolean variables, a, b, c that is a micro-optimization.
If we call 3 functions that return Boolean variables, each function may take a long time, and not only is it important to know this short circuits, but in what order. For example:
if (takesSeconds() && takesMinutes())
is much better than
if (takesMinutes() && takesSeconds())
if both are equally likely to return false.
That's why you can do in javascript code like
var x = x || 2;
Which would mean that if x is undefined or otherwise 'false' then the default value is 2.
In case someone's wondering if there is a way to force the evaluation of all condition, in some cases the bitwise operators & and | can be used
var testOr = true | alert(""); //alert pops up
var testAnd = false & alert(""); //alert pops up
These should be used really carefully because bitwise operators are arithmetic operators that works on single bits of their operand and can't always function as "non short-circuit" version of && and ||
Example:
-2147483648 && 1 = 1
but
-2147483648 & 1 = 0
Hope it helps someone who arrived here looking for information like this (like me) and thanks to #Max for the correction and the counter-example
It will only test all the conditions if the first ones are true, test it for yourself:
javascript: alert (false && alert("A") && false);
It short circuits - only a and b will be compared in your example.
Another reason why stopping evaluation with 1 or more parameters to the left.
if (response.authResponse && (response.authResponse.accessToken != user.accessToken)){
...
}
the second evaluation relies on the first being true and won't throw a compile error if response.authResponse is null or undefined etc because the first condition failed.
Other languages had this problem in the early days and I think it's a standard approach in building compilers now.
It exits after seeing that b does not equal one.
For anyone on this question confused because they're not seeing the short-circuit behaviour when using an || in conjunction with an ? operator like so:
x = 1 || true ? 2 : 3 // value of x will be 2, rather than 1 as expected
it seems like the short circuit rule isn't working. Why is it evaluating the second term of the || (true ? 2 : 3) when the first is true? It turns out to be an order of operations problem because the above is the equivalent of
x = (1 || true) ? 2 : 3
with the || evaluated first and the ? evaluated second. What you likely want is:
x = 1 || (true ? 2 : 3)
For this case:
a = 1
b = 2
c = 1
if (a==1 && b==1 && c==1)
You can use:
if ([a, b, c].every(x => x == 1))
// do something if a, b and c are equal to 1.
If you want to know if at least one is equal to 1, use the some() method instead of every():
if ([a, b, c].some(x => x == 1))
// do something if a, b or c is equal to 1.
every() and some() are array methods.

Categories