While practicing JavaScript, I revised an important concept:
Short-circuit evaluation using the OR (||
) and AND (&&
) operators.
πΉ OR (||
) Operator
The OR operator checks values from left to right and stops when it finds the first truthy value.
It then returns that value.
console.log(0 || "Hello" || 5);
// "Hello" β because 0 is falsy, "Hello" is the first truthy value
πΉ AND (&&
) Operator
The AND operator also checks values from left to right, but it stops when it finds the first falsy value.
If all values are truthy, it returns the last value.
console.log(1 && "Hello" && 100);
// 100 β all are truthy, so it returns the last value
console.log(1 && 0 && "Hello");
// 0 β stops at first falsy value
πΉ Easy Formula
-
||
β Stop at true β -
&&
β Stop at false β
β¨ Why is this important?
Short-circuiting is widely used in real-world code, for example:
- Providing default values:
const username = inputName || "Guest";
- Checking conditions safely:
user && user.profile && user.profile.email
This small but powerful concept makes JavaScript cleaner and easier to write.
π‘ ##GitHub Linkπ:
https://github.com/Usamaazeem03/The-Ultimate-React-Course.git
Top comments (0)