DEV Community

Usama
Usama

Posted on

πŸš€ Understanding JavaScript Short-Circuit Evaluation: || and &&

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
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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";
Enter fullscreen mode Exit fullscreen mode
  • Checking conditions safely:
  user && user.profile && user.profile.email
Enter fullscreen mode Exit fullscreen mode

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)