본문 바로가기

Programming/JavaScript

The Conditional (Ternary) Operator

ternary: composed of three parts

The ternary operator evaluates the test condition.

If the condition is true , expression1 is executed. If the condition is false , expression2 is executed.

https://www.programiz.com/javascript/ternary-operator

 

JavaScript Ternary Operator (with Examples)

A ternary operator can be used to replace an if..else statement in certain situations. Before you learn about ternary operators, be sure to check the JavaScript if...else tutorial. What is a Ternary operator? A ternary operator evaluates a condition and e

www.programiz.com

 

const age = 15;
age >= 18 ? console.log('와인은 으른만 마실 수 있다 🍷') : console.log('꼬꼬마는 물을 마셔야지 💧');

조건에 부합하면 : colon 앞에 콘솔문이 실행됨

If not, 뒤에 콘솔문 실행됨!

 

const drink = age >= 18 ? 'wine 🍷' : 'water 💧';
console.log(drink);

expression (value를 생성하는)으로 표현하는 방법도 있음.

여기선 drink로 const를 선언할 때 조건에 대한 결과값도 아예 같이 담아줌

 

let drink2;
if (age >= 18) {
    drink2 = 'wine 🍷';
} else {
    drink2 = 'water 💧';
}
console.log(drink2);

 

아예 콘솔문에 넣어주는 방법도 있음

흠.. 요건 눈에 잘 들어오진 않을듯

console.log(`I like to drink ${age >= 18 ? 'wine 🍷' : 'water 💧'}`);