JS - conditional

suyeon·2022년 9월 29일
0

Vanilla.js

목록 보기
5/13

conditional

: 조건문.
if...else문.

if (condition) {
  //executed if the condition is true. 
    } else {
      //executed if the condition is false.
}
  1. if뒤에 바로 오는 소괄호()에는 조건이 들어간다. true 혹은 false를 리턴.
  2. else안의 코드는 조건이 false를 반환할 때 실행된다.

if... else if...

// are you allowed to drink?
const age = parseInt(prompt("How old are you?"));

if (isNaN(age)) {
  alert("Please type in your real age.");
} else if (age < 18) {
   console.log("You are too young to drink.");
} else if (age >= 18 && age <= 50) {
  console.log("You can drink.");
} else if (age > 50 && age <= 80) {
  console.log("You shouldn't drink too much.");
} else if (age > 80) {
  console.log("Always be happy.");
}

++ MDN 예시: 아이가 부모님의 쇼핑을 도와주면 10달러를 용돈으로 받게 되고, 도와주지 않는다면 5달러를 받게 되는 조건문.

let shoppingDone = false;
let childsAllowance; 

if (shoppingDone === true) {
  childsallowance = 10;
} else {
  childsAllowance = 5;
}

연산자
: 1. && = 논리 연산자 AND. 한 쪽이 false면 조건 자체가 false가 된다.

true && true === true; //both of the statements should be true for condition to be true. 
true && false === false;
false && true === false;
false && false === false;
  1. || = 논리 연산자 OR. 한 쪽만 true여도 조건은 true가 된다.
true || true === true;
true || false === true;
false || true === true;
false || false === false; // both of the statements have to be false for condition to be false.
  1. ! = 논리 연산자 NOT. true연산자를 false로 반환.
const happy = !true; // false 반환
const sad = !false; // true 반환
  1. 비교연산자
    ==: 동등.
    !=: 부등.
    ===: 일치.
    !==: 불일치.
  • =====의 차이
    : ===는 비교하는 변수의 값 뿐만 아니라 변수의 유형까지 고려한다. 반면 ==의 경우, 변수 값을 기반으로 변수의 유형을 수정한다.
//==비교연산자
1 == '1' //true
1 == true //true
0 == [] //true
null == undefined //true

//===비교연산자
1 === '1' //false
1 === true // false
'true' === true //false

//cf1
true == 'true' //false. true는 1로 변환되고 'true'는 NaN으로 변환되기 때문에 이 statement는 거짓이다. 
//cf2
undefined == 'undefined' // false. undefined의 숫자형은 NaN, 'undefined'역시 NaN으로 변환. NaN == NaN이 false이기 때문에 반환되는 값은 false.

(❗️마지막 cf는 https://stackoverflow.com/questions/11363659/why-does-true-true-show-false-in-javascript 참조)


isNaN: 데이터 타입이 number가 아닌지 맞는지 구별해주는 function. true 혹은 false를 반환한다.

const a = 5;
console.log(isNaN(a)); // false 반환.

const b = "hello";
console.log(isNaN(b)); //true 반환. 

참고

profile
coding & others

0개의 댓글