Javascript

(Javascript) 연산자

JJeongHyun 2023. 1. 12. 23:24
반응형

연산자 (Operator)

  • JS에서는 여러 종류의 다양한 연산자(operator)를 제공
  • 종류
    • 산술, 문자열, 증감, 비교, 대입, 삼항, 논리, 비트연산자

 

산술연산자

  • 더하기
    • 숫자는 서로의 값을 더해주고, 텍스트(글자)는 붙여준다.
    • 숫자랑 텍스트를 더하기 연산하면 그냥 글자취급하여 붙여준다.
let plus1 = "자료 ";
let plus2 = "구조";
let plus3 = 3;
console.log(plus1 + plus2);
console.log(plus1 + plus3);

plus1 + plus2 / plus1 + plus3

  • 빼기, 곱하기, 나누기 연산자들은 숫자에서만 사용한다.
  • % 연산자는 나머지를 연산하는 명령어이다.
console.log(4 / 3);
console.log(4 % 3);
console.log(5 % 3);

위 코드 결과 값

 

 

증감연산자

  • ++, --
    • 변수에 1을 더하거나 1을 빼줍니다. 
    • ++나 --를 붙이는 위치에 따라서 결과가 달라질 수 있습니다.
      • 앞에 붙으면 전위증감연산자, 뒤에 붙으면 후위증감연산자
let count = 0;

console.log(++count); // 더하고 count를 출력한다.
console.log(--count); // 빼고 count를 출력한다.
console.log(count++); // 출력하고 count를 하나 늘린다.
console.log(count--); // 출력하고 count를 하나 뺸다.

위 코드에 대한 결과 값

 

대입연산자

  • 변수의 값을 정의할 때 사용한다
let test = 1;
// +=, -=, *=, /=, %=, **=
test += 2;
// test = test + 2;
test -= 2;
// test = test - 2;
test *= 2;
// test = test * 2;
test %= 2;
// test = test % 2;

test 연산 결과 값

 

비교연산자

  • 2개의 변수를 비교해서 boolean값으로 반환받을 수 있다
  • 종류
    • == : 값이 같음
    • === : 값과 자료형까지 같음
    • ! = : 같이 다름
    • ! == : 값과 자료형 까지 다름
const test2 = 1;
const test3 = 2;
const test4 = 1;
const test5 = "1";

console.log(test2 == test3);
console.log(!(test2 == test3));
console.log(test2 == test4);
console.log(test2 == test5);

console.log(test2 === test5);

console.log(test2 != test3);
console.log(test2 != test4);
console.log(test2 != test5);

console.log(test2 !== test5);

각 비교연산자를 통한 결과 값

대소연산자

  • 2개의 변수를 비교해서 boolean값으로 반환 받을 수 있다
  • 종류
    • < : 초과
    • > : 미만
    • <= : 이상
    • >= : 이하
console.log("test2 보다 초과");
console.log(test2 < test3);
console.log(test2 < test4);
console.log(test2 < test5);

console.log("test2 보다 미만");
console.log(test2 > test3);
console.log(test2 > test4);
console.log(test2 > test5);

console.log("test2 보다 이상");
console.log(test2 <= test3);
console.log(test2 <= test4);
console.log(test2 <= test5);

console.log("test2 보다 이하");
console.log(test2 >= test3);
console.log(test2 >= test4);
console.log(test2 >= test5);

대소연산자에 대한 결과