본문 바로가기

■ 프로그래밍/JavaScript

연산자(Operators) (1) - 숫자 관련

자바스크립트 연산자로 다양한 작업을 할 수 있다.

연산자는 크게 산술연산자(Arithmetic Operators), 대입연산자(Mathmatical Assignment Operators) 그리고 증감연산자(Increment and Decrement Operator)가 있다. 

 

산술연산자(Arithmetic Operators)

1. 더하기(Add): +

2. 빼기(Subtract): -

3. 곱하기(Multiply): *

4. 나누기(Divide): /

5. 나머지(Remainder): %

console.log(3 + 4); // output: 7
console.log(5 - 1); // output: 4
console.log(4 * 2); // output: 8
console.log(9 / 3); // output: 3
console.log(11 % 3); // output: 2, 11 나누기 3의 나머지는 2라서

나머지(%)는 주로 함수를 이용한 반복문을 만들때 사용된다. 

 

대입연산자(Mathematical Assignment Operators)

한 변수의 증감을 표현하기 위해서는 아래와 같이 쓸 수 있다. 

let a = 4;
a = a + 1; // a+1을 a에 넣는다
console.log(a); // output: 5

이는 아래와 같은 방법으로도 표현이 가능하다.

let a = 4;
a += 1; // a+1을 a에 넣는다
console.log(a); // output: 5

대입연산자에는 +=을 제외하고도 -=, *=, /=도 존재한다. 

let x = 20;
x -= 5; // x = x-5
console.log(x); // output: 15

let y = 50;
y *= 2; // y = y*2
consol.elog(y); // output: 100

let z = 8;
z /= 2; // z = z/2
console.log(z); // output: 4

 

증감연산자(Increment and Decrement Operator)

증감연산자는 ++, --가 있는데, 해당 변수에서 값을 1씩 증가하거나 감소하는 것이다. 

let a = 10;
a++;
console.log(a); // output: 11

let b = 10;
b--;
console.log(b); // output: 9

증감연산자에는 전위, 후위 연산자로 존재하는데 이는 증감과 할당의 전후 차이로 나뉜다. 

// 전위연산자
let i = 0;
console.log(++i); // output: 1, i에 1 증가한 값을 할당 후 결과 값 출력

// 후위연산자
let i = 0;
console.log(i++); // output: 0, i에 아직 1 증가를 할당하지 않은 채로 결과 값 출력
console.log(i); // output: 1

보통 for문에서는 후위연산자를 많이 쓴다.