Last active
October 30, 2020 17:03
-
-
Save danba340/862f389f6d8baba51070e3bd47c0bab0 to your computer and use it in GitHub Desktop.
JS Ternary operator use cases
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
// conditional ? expression1 : expression2 | |
// Variable assignments | |
const num = 20 | |
const numDescription = num > 9 ? "10 or bigger" : "less than 10"; | |
console.log("num is " + numDescription) | |
// Returning values | |
function getCost(isMember) { | |
return isMember ? '$1.00' : '$2.00'; | |
} | |
console.log("Cost for member " + getCost(true)) | |
// Assigning object property values | |
const macBook = { | |
model: "Macbook Air", | |
processor: 2020 < new Date().getFullYear() ? "ARM": "x86" | |
} | |
console.log(macBook) | |
// Evaluation multiple expressions | |
function logger(logEntry) { | |
logEntry.severity > 4 ? | |
(console.log("!!Danger!!"), console.log(logEntry.message)) : console.log(logEntry.message) | |
} | |
const logEntry = { | |
severity: 5, | |
message: "Security breach" | |
} | |
logger(logEntry) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment