2.10 Conditional branching: if, "?"

히진로그·2022년 1월 29일
0

Modern-Javascript

목록 보기
7/14

출처: https://javascript.info/

  • 혼자 읽고 타이핑하며 이해하면서 공부한 흔적 남기기

If와 '?'를 사용한 조건 처리

? : conditional operator, also called a 'question mark' operator.

The 'if' statement

The if(...) statement evaluates a condition in parentheses and, if the result is true, executes a block of code.

괄호안의 조건을 평가하여 결과가 true이면 코드 블럭을 실행한다.

let year = prompt('In which year was ECMAScript-2015 specification punlished?','');
if(year == 2015) alert('You are right!');

If we want to execute more than one statement, we have to wrap our code block inside curly braces.

하나 이상의 구문을 실행하고 싶다면 {} 괄호로 코드 블럭을 감싸준다.

We recommend wrapping your code block with curly braces {} every time you use an if statement, even if there is only one statement to execute. Doing so improves readability.

가독성을 위해 하나의 구문을 실행하더라도 if문을 쓸때는 {}로 코드블럭을 감싸는 것을 추천한다.

Boolean conversion

The if (...) statement evaluates the expression in its parentheses and converts the result to a boolean.

Several conditions: 'else if'

There can be more else if blocks. The final else is optional.

Conditional operator '?'

Sometimes, we need to assign a variable depending on a condition.

상황에 따라 변수를 지정할 필요가 있다.

let accessAllowed;
let age = prompt('How old are you?', '');

if(age > 18) {
	accessAllowed = true;
} else {
	accessAllowed = false;
}

alert(accessAllowed);

The operator is represented by a question mark ?. Sometimes it's called 'ternary'.

let result = (condition) ? value1 : value2;

The condition is evaluated: if it's truthy then value1 is returned, otherwise - value2.

parentheses make the code more readable.

Multiple '?'

A sequence of question mark operator ? can return a value that depends on more than one condition.

= if & else if

0개의 댓글