Forked from djD-REK/What Is The Short-Circuit Operator in JavaScript && (Logical AND) 2.js
Created
December 17, 2020 23:16
-
-
Save DoctorDerek/72ce6e43b563a82ea3a34a2729443918 to your computer and use it in GitHub Desktop.
What Is The Short-Circuit Operator in JavaScript && (Logical AND) 2
This file contains hidden or 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