Created
December 15, 2020 23:52
-
-
Save djD-REK/1690b6464df875b2971b22100295b278 to your computer and use it in GitHub Desktop.
What Is The Short-Circuit Operator in JavaScript && (Logical AND) 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// && 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