본문 바로가기

Javascript

문자열 / 템플릿 리터럴 / 산술, 증감, 대입연산자

# 연산자 : 데이터 값 반환

1️⃣ 문자열 붙이기 : + 를 사용하여 문자열을 이어 붙임. / 문자열과 숫자를 이어붙이면 숫자가 문자로 인식된다.

console.log('My' + ' car') // My car를 출력

console.log('1' + 2) // 12를 출력

console.log(1 + 2) // 3을 출력

 

  ✅템플릿 리터럴 (Template literals) : 백틱(``) 을 사용하여 문자열 데이터를 표현할 수 있다. 이중 따옴표나 작은 따옴표로 문자열을 표현할 때보다 <간결하게 문자열 붙이기가 가능>.

const shoesPrice = 200000

console.log(`이 신발의 가격은 ${shoesPrice}원입니다`)

// console.log('이 신발의 가격은 ' + shoesPrice + '원입니다') 와 같은 문자열 이어 붙이기와 동일

// + 를 활용한 문자열 붙이기보다 간결하게 표현할 수 있다.

 

2️⃣ 산술연산자 (Numeric operators)

  • 숫자 데이터에 대한 여러 연산들이 가능
  • 우리가 일상생활에서 많이 쓰는 사칙연산(+, -, *, /) 뿐만 아니라 // (나머지 연산), ** (거듭제곱) 도 가능

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을 출력

 

3️⃣ 증감연산자 (Increment and Decrement operators)**

자기 자신의 값을 증가시키거나 감소시키는 연산자(++, —)라고 생각하면 좋다. 이 증감연산자를 변수 앞에 놓는냐, 변수 뒤에 놓느냐에 따라 차이가 있다.

let count = 1
const preIncrement = ++count
// 증감연산자를 앞에 놓게 되면 아래 주석으로 처리한 두 줄의 코드와 같은 내용이다.
// 먼저 자기 자신에게 1을 더해서 재할당 한 후, 이를 preIncrement 에 할당했다는 의미.
// count = count + 1
// const preIncrement = count
console.log(`count: ${count}, preIncrement: ${preIncrement}`) 

// count: 2, preIncrement: 2

let count = 1
const postIncrement = count++
// 증감연산자를 뒤에 놓게 되면 아래 주석으로 처리한 두 줄의 코드와 같은 내용이다.
// postIncrement에 자기 자신의 값을 먼저 할당하고, 이후에 1을 더해서 재할당한다. 
// const postIncrement = count
// count = count + 1
console.log(`count: ${count}, postIncrement: ${postIncrement}`) 

// count: 2, postIncrement: 1 

 

⛔ count 변수를 const 가 아닌 let 구문으로 선언한 이유는 증감연산자를 활용해 count의 값을 계속 증가시키고 다시 count에 할당하고 있기 때문에 const를 사용하면 에러가 발생함.

 

4️⃣ 대입연산자 (Assignment operators)

  • 앞서 어떤 값을 어떤 변수에 할당한다는 표현을 많이 했다. 그게 바로 대입연산자를 사용한다는 의미.
  • = 뿐만 아니라 +=, -= 같은 것들을 통해서 연산과 대입을 한번에 할 수도 있다.

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 출력