TIL 13. JS 조건문

rahula·2021년 5월 13일
0

javascript

목록 보기
5/15
post-thumbnail

javascript의 조건문 (if & else, switch)과 무엇이 참인지에 대해서 알아보겠습니다. 이 글은 mdn을 토대로 쓰여졌습니다.

IF & ELSE

if문

if문은 ()안의 조건이 참인 경우에 { }안에 주어진 코드를 실행한다. if문은 기본적으로 조건이 거짓인 경우에는 실행하지 않으며, false인 경우에 대한 코드를 쓰고 싶다면 else 혹은 else if문안에서 실행할 수 있다.

그런데, 무엇이 참이고 무엇이 거짓일까?

Boolean conversion(변환)

if문은 조건을 평가할 때 모든 조건을 boolean 타입으로 변환한다. true 혹은 false 두 값만이 조건으로써 유효하기 때문이다.

자바스크립트에서, 참인 값은 Boolean인지 아닌지를 따지는 맥락에서 참이라고 고려된 값을 말한다. 모든 data값은 그것이 거짓이라고 정의되지 않은 한, 모두 참이다.

예외 : 값이 false가 아님에도, boolean으로 변환되었을 때 false가 되는 값들이 있다. 0, -0, 0n, "", null, undefined, NaN은 boolean으로 변환되었을 때 모두 false가 된다.

여기서 신기했던 점은, 조건으로써 들어간 data값이 예외적으로 false로 변환되는 값이 아닌 이상, 모두 true가 된다는 것이다. 그렇다면 저 값들이 아닌 모든 값, 말 그대로 거의 모든 값은 조건으로써 들어갈 때 true가 된다.

자바스크립트에서, 대부분의 data는 값으로써 존재하기만 해도 조건문 () 안에서 true로써 인식된다.

const func = ()=>{
  console.log("hi")
}
const arr = [1,2,3]
const obj = { a: 'apple'}

if(func){
  console.log("it's true!") // it's true!
}

if(arr){
  console.log("it's true!") // it's true!
}

if(obj){
  console.log("it's true!") // it's true!
}

else문

With an else statement, an alternate block of code can be executed after if.

function test(myCondition) {
  if (myCondition) {
    return "It was true";
  } else {
    return "It was false";
  }
}

test(true);
// "It was true"
test(undefined);
// "It was false"
test(1);
// "It was true"
test(1 === 2);
// "It was false

Else If문과 else if chain

우리는 else if를 여러 개 씀으로써 코드를 여러 조건에 따라 분기를 나눠 실행할 수 있다.
else if를 쓸 때 주의할 것은, 조건이 위에 있을수록 조건들 중에서 까다로워야(?) 한다는 것이다.

function bar(x) {
  if (x < 200) {
    return "Less than two";
  } else if (x < 100) {
    return "Less than one";
  } else {
    return "Greater than or equal to two";
  }
}

bar(110);
// "Less than two"
bar(10);
// "Less than two", which is not expected.

Conditional operator '?'

?:는 if else문의 단축문으로써 자주 쓰인다.

// 조건 ? true일 경우 : false일 경우
1 > 100 ? console.log("correct") : console.log("wrong");
// "wrong"
100 > 1 ? console.log("correct") : console.log("wrong");
// "correct"

?연산자가 유용한 경우가 하나 더 있다. 조건에 따라 값이 달라지는 변수를 선언할 때이다. ?연산자를 쓰지 않는다면, 우리는 변수를 let으로 선언한 뒤에 조건문 안에서 값을 할당해야 한다. 그러나 ?연산자를 쓰면 변수를 const로 선언할 수 있다. 그리고 const로 변수를 선언한다는 것은 코드 안에서 해당 변수의 값이 우발적으로 바뀔 일이 없다는 것이므로, 코드가 더 안정적이게 된다.

let userType;
if (userIsYoungerThan18) {
  userType = "Minor";
} else {
  userType = "Adult";
} 

const userType = userIsYoungerThan18 ? "Minor" : "Adult";

또한 이 연산자를 뒤에 연결해서 else if문을 만들 수 있다.

const userType = userIsYoungerThan3 
	? "Baby" : userIsYoungerThan10 
	? "Too young" : userIsYoungerThan18
	? "Minor" : "Adult";

Logical 'And' Operator

만약 false조건에 대한 코드가 필요하지 않다면, &&연산자를 통해서 더 줄여쓸 수 있다. &&는 앞에 오는 조건이 true일 경우에 뒤의 코드를 실행한다.
The logical and operator (&&) returns true if and only if the operands to the left and right of it are true.

Switch문

switch문은 본질적으로 if else와 같지만, 한 가지의 데이터에 대해서 많은 경우의 수(옵션)를 필요로 할 때, 코드를 간결하게 하기 위해 자주 쓰인다.

case values are tested with strict equality (===). The break tells JavaScript to stop executing statements. If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch.

const fruit = 'Mangoes';

switch (fruit) {
  case 'Oranges':
    console.log('Oranges are $0.59 a pound.');
	break;
  case 'Mangoes':
  case 'Papayas':
    console.log('Mangoes and papayas are $2.79 a pound.');
    // "Mangoes and papayas are $2.79 a pound."
    break;
  default:
    console.log(`Sorry, we are out of ${fruit}.`);
}
profile
백엔드 지망 대학생

0개의 댓글