ONLY use the following ternary operator and short circuit evaluation in simple use cases where it is obvious what your code is doing
This operator is frequently used as a shortcut for the if statement.
1<boolean> ? <expression if true> : <expression if false>
1condition ? expr1 : expr2
Note that you can not use return
statements in ternary operators. The conditional operator requires expressions, not statements. 1. In other words, it’s a conditional, you are assigning values, not returning things.
Stop code execution as soon as possible (in order to optimize code). It is old practice though so you won’t see it much. It works well for plain old if
statements and not that well with if .. else
.
1/*
2&&
3*/
4console.log(3 === 3 && 'cow') //cow (strings with a length >0 are truthy)
5console.log(3 === 3 && 'cow' && 'chicken') //chicken // all conditions are true
6console.log(3 === 3 && false && 'chicken') //false // will stop at first false operand
73 === 3 && false && console.log('chicken') //false // will not run console.log()
8
9
10/*
11||
12*/
13console.log(3 === 3 || 'cow') //true
14console.log(3 === 4 || 'cow' || 'chicken') //cow // cow is the first truthy value the interprator comes to
15console.log(3 === 3 || false || 0) //0 // if all values are false, it'll still return the last value
1function isAdult(age) {
2 if (age && age >= 18) {
3 return true;
4 } else {
5 return false;
6 }
7}
8console.log(isAdult());
is the same as
1function isAdult(age) {
2 return age && age >= 18;
3}
4console.log(isAdult());
Another way short circuiting is used is to set default values. For example,
1function countToFive(start) {
2 start = start || 1;
3 for (var i = start; i <=5; i++) {
4 console.log(i);
5 }
6}
here, for start = start || 1
if no start
argument is provided for your function, the first part of the statement will return false and move to the next, which is 1
.
WARNING: This is old practice and will give you issues if you pass in 0
as a value, since 0 will return false
. In ECMAScrit 2015, you can set default values for parameters.
1function countToFive(start = 1) {
2 for (var i = start; i <=5; i++) {
3 console.log(i);
4 }
5}
Here is another example of short circuit evaluation.
1function greet(name) {
2 name && console.log('Hi ' + name + '!');
3}