Just saw a line of code: a && b && c
. I think this should be equivalent to if(a && b) {c}
. But I'm really curious that is there any performance difference on these code, or it's just simply cool to put it in one line?
This is actual code: sourcesPanel && sourcesPanel.tips && sourcesPanel.tips.clearTimers()
The sourcesPanel
and sourcesPanel.tips
are two objects in the program.
Basically, I think it's checking if those two objects exist, it they exist, call that clearTimers
function.
Just saw a line of code: a && b && c
. I think this should be equivalent to if(a && b) {c}
. But I'm really curious that is there any performance difference on these code, or it's just simply cool to put it in one line?
This is actual code: sourcesPanel && sourcesPanel.tips && sourcesPanel.tips.clearTimers()
The sourcesPanel
and sourcesPanel.tips
are two objects in the program.
Basically, I think it's checking if those two objects exist, it they exist, call that clearTimers
function.
- 1 Where did you see it? Depends on the context. – rafaelc Commented May 15, 2015 at 17:32
-
if it was like
if(a && b && c)
then it means if all conditions are true then execute the next statement. – Abozanona Commented May 15, 2015 at 17:33 - @YazanWYusuf No it's not in if, just the line stand alone. – CodTango Commented May 15, 2015 at 17:35
3 Answers
Reset to default 3The logical operators in JS have a very important behavior: they return the first conclusively failing or succeeding operand. If does not.
The behavior of if (a) { if (b) { ...
is pretty simple: if they are truthy, enter the block.
The behavior of &&
is different:
foo = 1 && 2 && 3; // foo = 3, succeeds all the way through
foo = 1 && 0 && 3; // foo = 0, failed at 0
foo = 1 && null && 3; // foo = null, failed at null
When the logical operators are used within an if
, the behavior appears to be exactly the same. Used on their own or with an assignment, they behave in a relatively unexpected way.
Take the use of ||
to provide defaults:
opt = opt || {foo: bar};
If opt
was truthy (for an object, present) use it, otherwise use the defaults. The other logical operators behave the same way.
That is actually a double check and not a simple conditional check like you sugest: if(a && b) {c}
.
The equivalent to a && b && c
would be:
if (a && b){
if(c){
// do something
So all a
, b
and c
have to be truthy.
a && b && c
is mostly more practical than doing
if (a){
if (b){
if(c){
// do something
But in a triple check like a && b && c
b
will never be evaluated if a
evaluates false
. Thus sparing time. The same for c
that will only be evaluated if a
and b
also were true.
There is a performance improvement in some circumstances.
The line is executed step by step from left to right, and leaves as soon as it fails.
So, if a is false, b and c will not be evaluated.
You see this a lot in bash where one instruction is dependent upon another succeeding, but the first has to be attempted no matter what.