-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTernary.js
More file actions
37 lines (26 loc) · 901 Bytes
/
Ternary.js
File metadata and controls
37 lines (26 loc) · 901 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// The ternary operator is the only operator in JavaScript that takes 3 operands, hence "ternary."
// This is also called the conditional ternary operator, as it allows you to evaluate some condition
// and then execute some expression depending on the condition.
// The syntax will be as follows:
// condition ? exp1 : exp2
// ? checks if the condition is truthy
const age = 26;
const legalAge = 21;
const drink = age >= legalAge ? 'Beer' : 'Juice';
console.log(drink);
// Commonly used to check for null
const greeting = (person) => {
const name = person
? person.name
: "stranger";
return `Howdy, ${name}`;
};
console.log(greeting({ name: 'Alice' }));
console.log(greeting(null));
// Not great practice to nest ternary but you can
function example() {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}