"Boldness has genius, power, and magic in it." - Johann Wolfgang von Goethe

JavaScript

[JS] JS 조건문, 반복문, 변수, 형 변환 문법정리

Toproot 2021. 7. 13. 13:08
728x90
728x90

 

🍯 조건문 if, else

import random from './getRandom'

// 조건문 (If statement)

// console.log(random())

const a = random()

if (a === 0) {
  console.log('a is 0')
} else if (a === 2) { // if 조건이 false일때 넘어옴.
  console.log('a is 2')
} else if (a === 4) { // 맞으면 나머지 무시.
  console.log('a is 4')
} else {
  console.log('rest...')
}

 

🍯 조건문 Switch

  • 조건문 (Switch statement)
  • 깔끔해보이지만 수직으로 길어짐.
  • 값이 하나로 딱 떨어질 때 사용하면 효율적.
import random from './getRandom'

const a = random()

switch (a) {
  case 0:
    console.log('a is 0')
    break // 하나의 케이스가 끝나면 꼭 종료해주기!
  case 2:
    console.log('a is 2')
    break
  case 4:
    console.log('a is 4')
    break
  default:
    console.log('rest...')
}

 

🍯 반복문 For

  • for (시작조건; 종료조건; 변화조건) {}
  • 종료조건이 false가 되면 종료
// 반복문 (For statement)

const ulEl = document.querySelector('ul')

for (let i = 0; i < 10; i += 1) {
  const li = document.createElement('li')
  li.textContent = `list-${i + 1}` // 1부터 시작
  if ((i + 1) % 2 === 0) {
    li.addEventListener('click', function () {
    console.log(li.textContent)
    })
  }
  ulEl.appendChild(li)
}

 

🍯 변수 유효범위

  • let, const : 블록레벨의 유효범위를 가지고 있음
  • var : 함수 범위의 유효범위를 가지고 있음.
// 변수 유효범위(Variable Scope)
// var, let, const

function scope() {
  console.log(a)
  if (true) {
    var a = 123
  }
}
scope() // undefined

// let, const 였다면 오류발생.
// var는 함수범위라서 변수는 있지만 값은 지정되지 않은 상태.

 

🍯 형 변환

// 형 변환(Type conversion)

const a = 1
const b = '1'

// == : 동등 연산자
// 되도록이면 안쓰는 것 권장. 예외사황 발생(자동 형변환 발생)
// 웬만하면 일치연산자(===) 사용하기
console.log(a == b)

// Truthy(참 같은 값)
// true, {}, [], 1, 2, 'false', -12, '3.14' ...

// Falsy(거짓 같은 값)
// false, '', null, undefiend, 0, -0, NaN(Not a Number => 1 + undefined)

if ('false') {
  console.log(123)
}

 

 

 

 

 

728x90
728x90