js 연산자

니나노개발생활·2021년 5월 31일
0

🏃🏻‍♀️bootcamp

목록 보기
10/18

문자열 붙이기

  • +를 이용하여 문자열을 붙일 수 있다.
console.log('nayeong' + 'kim') //nayeong kim을 출력
  • 템플릿 리터럴
    : 백틱(``)을 사용하여 문자열 데이터를 보다 간결하게 붙일 수 있다.
const shoesPrice = 200000
console.log(`이 신발의 가격은 ${shoesPrice}원입니다`) 
// console.log('이 신발의 가격은 ' + shoesPrice + '원입니다') 와 동일

산술연산자

  • 사칙연산, 나머지, 거듭제곱도 가능하다.
console.log(2 + 1) // 3을 출력
console.log(2 - 1) // 1을 출력
console.log(4 / 2) // 2를 출력
console.log(2 * 3) // 6을 출력
console.log(10 % 3) // 나머지(remainder) 연산자. 1을 출력
console.log(10 ** 2) // exponentiation. 10의 2승인 100을 출력

증감연산자

  • 자기 자신의 값을 증가시키거나 감소시키는 연산자
  • 증감연산자를 변수 앞 또는 뒤 위치에 따라 차이가 있다.

let count = 1
const preIncrement = ++count

// count = count + 1                    // count변수에 1을 더해서 재할당 후
// const preIncrement = count           // 이를 preincrement에 할당시킨다.
console.log(`count: ${count}, preIncrement: ${preIncrement}`) // count: 2, preIncrement: 2

let count = 1
const postIncrement = count++ 
// const postIncrement = count           // count변수에 먼저 postincrement를 할당시킨 후
// count = count + 1                     // 이후에 1을 더하여 재할당한다.
console.log(`count: ${count}, postIncrement: ${postIncrement}`) // count: 2, postIncrement: 1 

🚨 count변수를 const가 아닌 let 구문으로 선언한 이유

  • 증감연산자를 이용해 count의 값을 계속 증가시키고 다시 count에 할당하고 있기 때문에 재할당이 가능한 let을 사용!

대입연산자

  • 할당한다는 표현이 대입연산자를 사용한다는 의미!
  • = / += / -=
const shirtsPrice = 100000
const pantsPrice = 80000
let totalPrice = 0

totalPrice += shirtsPrice // totalPrice = totalPrice + shirtsPrice 와 동일
console.log(totalPrice)     //100000이 출력
totalPrice += pantsPrice // totalPrice = totalPrice + pantsPrice 와 동일 
console.log(totalPrice)     //180000이 출력

totalPrice -= shirtsPrice // totalPrice = totalPrice - shirtsPrice 와 동일
console.log(totalPrice)     //80000이 출력

비교연산자

  • 값을 비교하며 조건문에서 많이 쓰인다
  • boolean으로 값을 얻을 수 있다.
console.log(1 < 2) // 1이 2보다 작은가? true
console.log(2 <= 2) // 2가 2보다 작거나 같은가? true
console.log(1 > 2) // 1이 2보다 큰가? false
console.log(1 >= 2) // 1이 2보다 크거나 같은가? false

논리연산자

  • || (or), && (and), ! (not)
  • || 는 연산 대상 중 하나만 true 여도 true 리턴
    && 는 연산 대상이 모두 true 여야만 true 리턴
    ! 는 true를 false로, flase를 true로 바꿔서 리턴

일치연산자

  • ===
console.log(1 === 1) // true
console.log(1 === 2) // false
console.log('Javascript' === 'Javascript') // true
console.log('Javascript' === 'javascript') // 대소문자나 띄워쓰기도 다 정확히 일치. 따라서 false

🚨'=='도 있고 '==='도 있고?
: === 는 엄밀한 (strict) 일치연산자여서 비교하는 두 값의 데이터타입과 값 자체가 정확히 일치해야만 true를 리턴한다.

console.log(1 === "1") // false를 출력
 //엄격한 일치연산자를 사용하고 있고 숫자 1과 문자열 1의 데이터타입이 다르기 때문에 false
console.log(1 == "1") // true를 출력
 //숫자 1과 문자열 1의 데이터타입이 다르나 '=='는 두 값으 데이터타입이 일치하지 않을 때 자동으로 변환해주는 js의 특성이 있다.
profile
깃헙으로 이사중..

0개의 댓글