I was going through a tutorial recently and I found out this developer kept using && operator to perform if statement. Take a look.
const status = true
function logSomething(){
console.log('hello world');
}
=========if way========================
if(status) logSomething();
===================and way ======================
status && logSomething();
They do the same thing .Thanks for reading
Top comments (3)
Yeah, it's called "short circuit".
I am taking my liberty to explain this concept in detail, since I get the feeling that this is new to you (appologies if I'm wrong):
It's just an evaluation of something / a condition. The
status && logSomething()
-part is evaluated.Actually the whole thing evaluates to
false
because a function that you don't explicitly return something from, will actually (implicitly) returnundefined
which is a falsy value and therefore evaluates tofalse
.Therefore you can do something like this:
and
console.log("Done")
would never execute (unless you return true or a truthy value from the function), but you would still see'hello world'
in the console...So, in the end:
is the same as:
Be carefull tho'! You can't do this:
which was the same as:
and we (hopefully) know that we can't assign values when checking a condition, since an assignment won't evaluate to
true
/false
.What we can do in this case:
Hope it gave some insight and better understanding of this concept...
You're wrong i think.
is not equal to
It is equal to
If you want to assign variables with Logical &&. You can do like this :
an other example :
but
Thanks for taking your time to explain