In this “If statement shorthand examples in JavaScript” post, I have a short example on Short-Circuit in JavaScript.
In the current post, I am just going to list few examples to understand it better rather than just theory.
&& Operator
Let’s check if a function returns true and if so, call a function. This is how we approach it conventionally.
if(adult){
ageValid();
}
But, we can just write this code and it will do the same thing in less code.
adult && ageValid();
The && operator will only go for the second condition if the first one is true otherwise it will stop execution after the first one.
|| Operator
Let’s check if the age of an adult is undefined then log an error. This is how we approach it conventionally.
if(adult.age === 'undefined'){
console.log('age unknown');
}
We can also just log the age and it will print “undefined” like this:
console.log(adult.age);
//undefined
But, we can just write this code and it will do the same thing in less code.
console.log(adult.age || 'age unknown' );
The || operator will check both conditions no matter the outcome of the first one.
You can check more than two conditions just like this example: a short example on Short-Circuit in JavaScript
examples if-else shorthand