This content originally appeared on DEV Community and was authored by DEV Community
It is always awesome to use a quick way to write simple like ternary operator.
// example 1:
let x = 3;
let answer = x > 5 ? true : false; // false since 3 is less than 5
// example 2:
let y = [1,2,3];
let z = [4,5];
let answer = y.includes(5) ? (z.includes(5) ? true : false) : false; // true
Ternary operator is good to use but not always. So javascript introduced a way to evaluate expressions. This are &&
(AND) and ||
(or).
How Does it Work?
1. && - this will return the first falsy
value. If all are true, return the last value;
console.log(5 && 6 && null && false && 0);
/**
result: null
- because the null is the first `falsy`.
*/
console.log(true && 1 && 4);
/**
result: 4
- because everything is `truthy`.
*/
let a = [1,2,3].includes(3) && 5 && 'good';
/**
result: 'good'
- because everything is truthy
*/
2. || - next is the || operator. Using || will return the first true or ‘truthy’ value. If every operand evaluates to false , the last evaluated expression will be returned.
console.log(5 || 6 || null || false || 0);
/**
result: 5
- because the 5 is the first `truthy`.
*/
console.log(false || 6 || null || false || 0);
/**
result: 6
- because the 6 is the first `truthy`.
*/
console.log(true || 1 || 4);
/**
result: true
- because true is thruthy.
*/
let a = [1,2,3].includes(3) || 5 || 'good';
/**
result: true
- because the first condition is truthy.
*/
This is very useful to make conditional statement smaller. Something Like This:
if (data) {
return data;
} else {
return 'No Data';
}
can be converted to:
return (data || 'No Data');
thanks for Reading Short Reads. If you like to donate, click the image.
This content originally appeared on DEV Community and was authored by DEV Community
DEV Community | Sciencx (2022-03-02T10:49:55+00:00) Short-Circuit Evaluation. Retrieved from https://www.scien.cx/2022/03/02/short-circuit-evaluation/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.