Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save djD-REK/1690b6464df875b2971b22100295b278 to your computer and use it in GitHub Desktop.
Save djD-REK/1690b6464df875b2971b22100295b278 to your computer and use it in GitHub Desktop.
What Is The Short-Circuit Operator in JavaScript && (Logical AND) 2
// && can be used to prevent errors, because the error won't be thrown.
const nullBanana = null
try {
console.log(nullBanana.length)
} catch (e) {
console.log(e)
}
// Output: "TypeError: null has no properties."
// Using && short-circuits the code, so the TypeError doesn't occur.
nullBanana && console.log(nullBanana.length)
// Nothing happens, since we never reach the nullBanana.length code.
// Both null and undefined are falsy values commmonly used with &&.
let banana // undefined
banana && "🍌" && console.log(banana.length) // nothing happens
// In comparison, strings are truthy, except for "" the empty string.
"🍌" && console.log("🍌") // 🍌
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment