JavaScript: JS 기초 Ep.5 (비교,논리 연산자, 삼항연산자, If, Switch, 반복문 for, 변수 유효범위, 형 변환)

비교, 논리 연산자


  • 비교 연산자 (comparison operator)
    // 일치 연산자
    const a = 1
    const b = 1
      
    console.log(a === b) // true
    -----------------------------
    // 일치 연산자를 이용한 함수 만들기
    function isEqual(x,y) {
      return x === y
    }
      
    console.log(isEqual(1, 1)) // true
    console.log(isEqual(2, '2')) // false
    -----------------------------
    // 불일치 연산자
    const a = 1
    const b = 1
      
    console.log(a !== b) // false
    -----------------------------
    // 비교 연산자
    console.log(a < b) // false
    console.log(a > b) // false
    console.log(a >= b) // true
    console.log(a <= b) // true
    
    • 일치 연산자 (===): 왼쪽의 데이터(a)와 오른쪽의 데이터(b)를 비교하여 서로 일치하는지 확인함 데이터 타입과 값 모두 일치해야만 true가 반환됨
    • 불일치 연산자 (!==): 왼쪽의 데이터(a)와 오른쪽의 데이터(b)를 비교하여 서로 불일치하는지 확인함 데이터 타입과 값 모두 불일치해야만 true가 반환됨
  • 논리 연산자 (logical operator)
    const a = 1 === 1
    const b = 'AB' === 'AB'
    const c = true
    const d = false
      
    console.log(a) // true
    console.log(b) // true
    console.log(c) // true
      
    console.log('&&: ',a && b && c) // true
    console.log('&&: ',a && b && d) // false
    console.log('||: ',a || b || c) // true
    console.log('||: ',a || b || d) // true
    console.log('!: ', a) // true
    console.log('!: ', !a) // false
    
    • and(그리고)연산자 ( && )
      해당 값들이 모두 동일해야만 true 반환한다. 하나라도 false라면 결과값은 false가 나온다.
    • or(또는)연산자 ( || )
      ture값이 하나이상 있다면 true를 반환한다. true 값이 하나라도 없어야 (모두 false여야) false값이 나온다.
    • not(부정)연산자 ( ! )
      ‘!’ 뒤 데이터가 true면 false 반환, false면 true를 반환한다. 해당 데이터의 반대되는 데이터 값을 반환한다.

삼항 연산자 (ternary operator)


말 그대로 항이 3개가 존재한다. (a, ‘참’, ‘거짓’)
? 를 기준으로 앞의 값이 true인지 false인지 확인한다.
만약 true라면, : 의 앞부분 실행, false면 : 의 뒷부분 실행

const a = 1 < 2  // a = true

if (a) {
	console.log('')
} else {
	console.log('거짓')
} // '참'

// 삼항 연산자 사용
console.log(a ? '' : '거짓') // '참'

조건문 (If, Switch)


  • If statement

    // getRandom.js
    export default function random() {
      return Math.floor(Math.random() * 10)
    }
    
    • export default는 해당 파일 밖으로 내보내기 위한 것이다.
    • Math 수학 객체를 사용하여 랜덤한 수를 반환한다.
    • 랜덤 수 * 10에 내림(floor) => 정수값만 나오도록한다.
    // main.js
      
    import random from './getRandom'
      
    const a = random()
      
    if (a === 0) {
      console.log('a is 0')
    } else if (a === 2) {
      console.log('a is 2') 
    } else if (a === 4) {
      console.log('a is 4') 
    } else {
      console.log('rest...')
    }
    
  • Switch statement

    import random from './getRandom'
      
    const a = random()
      
    switch (a) {
      case 0: // a 값이 0일때, a is 0 출력
        console.log('a is 0')
        break // break를 하지 않으면 멈추지 않고 다음 케이스가 실행될 수 있음
      case 2: // a 값이 2 일때
        console.log('a is 2')
        break
      case 4:
        console.log('a is 4')	
        break
      default: // case가 전부 해당 안될때, 마치 else 같은 것
        console.log('rest...')
        // 맨 마지막에 실행되는 것이기 때문에 break 필요 없음
    }
    

반복문 For


반복문 (For statement)
for (시작조건; 종료조건; 변화조건) {}

<html>
<head>
	<script defer src="./main.js"></script>
</head>
<body>
	<h1>Hello world!</h1>
	<ul></ul>
</body>
</html>
const ulEl = document.querySelector('ul')

for (let i = 0; i < 3; i += 1) {
	const li = document.createElement('li')
	li.textContent = `list-${i + 1}`
	ulEl.appendChild(li)
}

// Hello world!
// * list-1
// * list-2
// * list-3
  • 클릭한 요소의 값을 반환

    for (let i = 0; i < 10; i += 1) {
      const li = document.createElement('li')
      li.textContent = `list-${i + 1}`
      li.addEventListener('click', function () {
      console.log(li.textContent)
    }) //textContent -> 요쇼의 값을 지정, 요소가 갖고 있는 값을 얻어낼 수도 있다
      ulEl.appendChild(li)
    }
    
    // Hello world!
    // * list-1
    // * list-2
    // * list-3
    // * list-4
    ...
    // * list-10
    
    // list-2 클릭시 'list-2' 반환
    
  • 짝수 반환하기
    list-7 클릭 -> 반환
    list-8 클릭 -> 반환안됨
    => 문제 발생!

    for (let i = 0; i < 10; i += 1) {
    const li = document.createElement('li')
    li.textContent = `list-${i + 1}`
    if (i % 2 === 0) {
      li.addEventListener('click', function () {
        console.log(li.textContent)
      })
    } 
    ulEl.appendChild(li)
    }
    
    // 짝수값을 클릭했을때 값이 나오게 하고 싶은데!
    
  • 해결
    list-${i + 1} => (i + 1)
    if 조건또한 i가 아닌 i + 1로 한다.
    보이는 것만 1로 시작하게 설정했지 실제로는 0부터 시작(제로 베이스)이기 때문이다.

    for (let i = 0; i < 10; i += 1) {
      const li = document.createElement('li')
      li.textContent = `list-${i + 1}`
      if ((i + 1) % 2 === 0) {
        li.addEventListener('click', function () {
          console.log(li.textContent)
        })
      } 
      ulEl.appendChild(li)
    }
    
    // if 조건 부분의 i를 i+1로 변경하면 짝수 클릭시 출력, 홀수 클릭시 미출력
    

변수 유효범위 (Variable Scope)


var(되도록 사용 X), let, const

  • let, const
    블록 레벨의 유효범위를 가진다.
    블록 ⇒ 변수가 선언되어져 있는 그 범위의 중괄호{} 부분이 하나의 블록이다.
    이 블록 내부에서의 유효한 범위를 가질 수 있다.
  • var
    함수 레벨의 유효범위를 가진다.
    함수 범위 안에서라면 어디서든지 사용이 가능하다.
    만약, 값이 지정되기 전에 사용했다면 undefined라고 나오는 것이다. ⇒ 에러가 아니다!
    블록레벨보다 범위가 더 크기 때문에 의도하지 않은 범위 내에서 사용될 수 있다. 그만큼 메모리를 차지하게 되고 이것이 개발자가 확인하지 못하는 메모리 누수로 발전할 수 있다.
    그렇기에 var를 잘 사용하지 않는 것이다!!

    // let과 const -> 블록 레벨의 유효범위를 가짐
      
    function scope() {
      if (true) {
        const a = 123
        console.log(a)
      }
    }
    scope()
      
    // 123
    ----------------------------
    
    function scope() {
      if (true) {
        const a = 123
      }
      console.log(a)
    }
    scope()
      
    // ReferenceError
    ----------------------------
    
    function scope() {
      if (true) {
        console.log(a)
        const a = 123
      }
    }
    scope()
      
    // undefined
    ----------------------------
    
    function scope() {
      console.log(a)
      if (true) {
        const a = 123
      }
    }
    scope()
      
    // ReferenceError
    
    // var -> 블록이 아닌 함수 범위의 유효범위를 가짐
      
    function scope() {
      console.log(a)
      if (true) {
        var a = 123
      }
    }
    scope()
      
    // undefined
    ----------------------------
    
    function scope() {
      if (true) {
        var a = 123
      }
      console.log(a)
    }
    scope()
      
    // 123
    

형 변환 (Type conversion)


데이터 타입(형)들의 변환

  • 동등연산자 (==)

    자바스크립트를 사용할때 되도록 사용하지 않는 것을 권장한다. 의도하지 않게 다른 값을 같다라고 나올 수 있기 때문이다.
    대부분의 다른 언어에서는 ‘==’를 사용하지만 자바스크립트에서는 동등연산자(==)를 사용하면 형 변환이 일어난다.
    1과 ‘1’은 다른 타입이지만 타입변화(형 변환)가 일어나 같다고 나오게 된다. 그렇기에 자바스크립에서 비교할때는 ‘===’ 를 사용하자!

    const a = 1
    const b = '1'
      
    console.log(a === b)
    // false
      
    console.log(a == b)
    // true
    
  • 형 변환 정리

    if (true) {
      console.log(123)
    } //123
      
    if (false) {
      console.log(123)
    } // - 아무것도 반환되지 않음 - 
      
    if ('false') {
      console.log(123)
    } //123
    // 'false'(문자열)는 true와 같은 값이라고 보면 됨
    // 이것이 바로 자바스크립트의 형 변환!
      
    if (0) {
      console.log(123)
    } // - 아무것도 반환되지 않음 - 
      
    if (undefined) {
      console.log(123)
    } // - 아무것도 반환되지 않음 - 
    
    • Truthy (참 같은 값)
      true, {}, [], 1, 2, ‘false’, -12, ‘3.14’ …
    • Falsy (거짓 같은 값)
      false, ‘’ , null, undefined, 0, -0, NaN(Not a Number)

    • NaN (Not a Number)
      숫자 데이터이긴 하지만 숫자는 아닐때이다.
      되도록 나오지 않도록 해야 한다.
      1 + undefined // NaN

Comments