• Home
  • About
    • PI photo

      PI

      Beginner's Blog

    • Learn More
    • Github
  • Posts
    • All Posts
    • All Tags
    • All Categories
  • Projects

[JS] 조건문

📆 Created: 2024.11.10 Sun

Reading time ~2 minutes

목차

  • 1. if
    • 조건식
    • 비교연산자
    • 중첩
  • 2. switch
  • 3. 삼항연산자 ?

1. if … else

1.1. 문법

if (조건문) {
    statement 1
} else if (조건문) {
    statement 2
} else {
    statement 3
}
let data = 'test';

if(data === 'test') {
    console.log("Same!");
} else {
    console.log("Not Same");
}

1.2. 조건식 -> 거짓

  1. false
  2. undefined
  3. null
  4. 0
  5. NaN
  6. ””

1.3. 비교연산자

  1. ==, !=(Equal Operator): 한 값이 다른 값과 같거나 다른 지 판단
  2. ===, !==(Strict Equal Operator): 한 값이 다른 값과 데이터 타입이 같거나 다른 지 판단
  3. <, >: 한 값이 다른 값보다 큰지 작은 지 판단
  4. <=, =>: 한 값이 다른 값보다 크거나 같은지, 작거나 같은지 판단

1.3.1. ==/!= vs ===/!==

console.log(null == undefined); // true
console.log(null === undefined); // false

console.log(true == 1); // true
console.log(true === 1); // false

console.log(0 == "0"); // true
console.log(0 === "0"); // false

console.log(0 == ""); // true
console.log(0 === ""); // false

console.log(NaN == NaN); // false
console.log(NaN === NaN); // false

var a = [1,2,3];
var b = [1,2,3];
console.log(a == b); // false
console.log(a === b); // false

var a = [1,2,3];
var b = [1,2,3];
var c = b;
console.log(b === c); // true
console.log(b == c); // ture

var x = {};
var y = {};
var z = y;
console.log(x == y) // false
console.log(x === y) // false
console.log(y === z) // true
console.log(y == z) // true

1.4. 중첩

let a = 1;
let b = 2;
let c = 3;

if (a > b) {
    if (b > c) {
        console.log("a > b > c");
    } else if (a > c) {
        console.log("a > c > b");
    } else {
        console.log("c > a > b");
    }
} else {
    if (a > c) {
        console.log("b > a > c");
    } else if (b > c) {
        console.log("b > c > a");
    } else {
        console.log("c > b > a");
    }
}

2. switch

2.1. 문법

switch (변수) {
    case n1: // 값 n1
    변수 값이 n1일 때 실행할 명령문
    break;
    case n2: // 값 n2
    변수 값이 n2일 때 실행할 명령문
    break;
    case n3: // 값 n3
    변수 값이 n3일 때 실행할 명령문
    break;
    default:
    모든 case에 부합하지 않을 때 실행할 명령문
    break;
}
let x = 3;
switch (x % 3) {
    case 0:
        console.log("x = 3 * n");
    break;
    case 1:
        console.log("x = 3 * n + 1");
    break;
    case 2:
        console.log("x = 3 * n + 2");
    break;
    default:
        console.log("error");
    break;
}

3. 삼항 연산자 ?

3.1. 문법

(조건문) ? 참일 때 실행:거짓일 때 실행;
let a = 1;
let b = 2;
(a > b)?console.log("a>b"):console.log("b>a");

참고

  • 조건문 1
  • 조건문 2
  • == vs ===


JS Share Tweet +1
/#disqus_thread