newclass
2025. 3. 30. 18:51
연산자
JavaScript에서는 다양한 연산자를 사용하여 값을 조작할 수 있습니다. 연산자는 값에 대해 특정 연산을 수행하고 결과를 반환합니다.
1. 산술 연산자
산술 연산자는 수학적 계산을 수행합니다.
연산자 | 설명 | 예제 | 결과 |
+ | 덧셈 | 5 + 2 | 7 |
- | 뺄셈 | 5 - 2 | 3 |
* | 곱셈 | 5 * 2 | 10 |
/ | 나눗셈 | 5 / 2 | 2.5 |
% | 나머지 | 5 % 2 | 1 |
** | 거듭제곱 | 5 ** 2 | 25 |
++ | 증가 | let a = 5; a++; | a는 6이 됨 |
-- | 감소 | let a = 5; a--; | a는 4가 됨 |
// 산술 연산자 예제
let a = 10;
let b = 3;
console.log(a + b); // 13
console.log(a - b); // 7
console.log(a * b); // 30
console.log(a / b); // 3.3333...
console.log(a % b); // 1 (나머지)
console.log(a ** b); // 1000 (10의 3승)
// 증가/감소 연산자
let c = 5;
console.log(c++); // 5 (출력 후 증가)
console.log(c); // 6
console.log(++c); // 7 (증가 후 출력)
let d = 5;
console.log(d--); // 5 (출력 후 감소)
console.log(d); // 4
console.log(--d); // 3 (감소 후 출력)
// 문자열과 + 연산자
console.log("안녕" + "하세요"); // "안녕하세요" (문자열 연결)
console.log("숫자 " + 5); // "숫자 5" (숫자를 문자열로 변환 후 연결)
2. 할당 연산자
할당 연산자는 변수에 값을 할당합니다.
연산자 | 설명 | 예제 | 동일 표현 |
= | 기본 할당 | x = 5 | |
+= | 덧셈 후 할당 | x += 2 | x = x + 2 |
-= | 뺄셈 후 할당 | x -= 2 | x = x - 2 |
*= | 곱셈 후 할당 | x *= 2 | x = x * 2 |
/= | 나눗셈 후 할당 | x /= 2 | x = x / 2 |
%= | 나머지 연산 후 할당 | x %= 2 | x = x % 2 |
**= | 거듭제곱 후 할당 | x **= 2 | x = x ** 2 |
// 할당 연산자 예제
let x = 10;
console.log(x); // 10
x += 5; // x = x + 5
console.log(x); // 15
x -= 3; // x = x - 3
console.log(x); // 12
x *= 2; // x = x * 2
console.log(x); // 24
x /= 4; // x = x / 4
console.log(x); // 6
x %= 4; // x = x % 4
console.log(x); // 2
x **= 3; // x = x ** 3
console.log(x); // 8
// 여러 변수 한번에 할당
let a, b, c;
a = b = c = 5; // 모두 5로 할당
console.log(a, b, c); // 5 5 5
// 구조 분해 할당(ES6)
const [first, second] = [1, 2];
console.log(first, second); // 1 2
const { name, age } = { name: "홍길동", age: 25 };
console.log(name, age); // "홍길동" 25
3. 비교 연산자
비교 연산자는 두 값을 비교하고 결과로 불리언 값(true 또는 false)을 반환합니다.
연산자 | 설명 | 예제 | 결과 |
== | 동등(값만 비교) | 5 == "5" | true |
=== | 일치(값과 타입 모두 비교) | 5 === "5" | false |
!= | 부등(값만 비교) | 5 != "6" | true |
!== | 불일치(값과 타입 모두 비교) | 5 !== "5" | true |
> | 크다 | 10 > 5 | true |
< | 작다 | 10 < 5 | false |
>= | 크거나 같다 | 10 >= 10 | true |
<= | 작거나 같다 | 5 <= 10 | true |
// 비교 연산자 예제
// 동등(==)과 일치(===)
console.log(5 == 5); // true
console.log(5 == "5"); // true (타입 변환 후 비교)
console.log(5 === 5); // true
console.log(5 === "5"); // false (타입까지 비교)
// 부등(!=)과 불일치(!==)
console.log(5 != 8); // true
console.log(5 != "5"); // false (타입 변환 후 비교)
console.log(5 !== 8); // true
console.log(5 !== "5"); // true (타입까지 비교)
// 대소 비교
console.log(10 > 5); // true
console.log(10 < 5); // false
console.log(10 >= 10); // true
console.log(5 <= 10); // true
// 문자열 비교 (사전순)
console.log("apple" < "banana"); // true
console.log("apple" > "Apple"); // true (소문자가 대문자보다 코드값이 큼)
// 다른 타입 비교
console.log("123" > 100); // true (문자열이 숫자로 변환)
console.log(true == 1); // true (true는 1로 변환)
console.log(false == 0); // true (false는 0으로 변환)
console.log(null == undefined); // true
console.log(null === undefined); // false
4. 논리 연산자
논리 연산자는 불리언 값을 조합하고 논리적 판단을 수행합니다.
연산자 설명 예제 결과
&& | 논리 AND | true && false | false |
|| | 논리 OR | true || false | true |
! | 논리 NOT | !true | false |
// 논리 연산자 예제
const isAdult = true;
const hasPermission = false;
// 논리 AND (&&) - 모든 조건이 참이어야 참
console.log(isAdult && hasPermission); // false
console.log(true && true); // true
// 논리 OR (||) - 하나 이상의 조건이 참이면 참
console.log(isAdult || hasPermission); // true
console.log(false || false); // false
// 논리 NOT (!) - 결과를 반전
console.log(!isAdult); // false
console.log(!hasPermission); // true
// 복합 논리 연산
console.log((5 > 3) && (2 < 4)); // true
console.log((5 < 3) || (2 > 4)); // false
console.log(!(5 > 3)); // false
// 단축 평가(short-circuit evaluation)
console.log(true && "Hello"); // "Hello" (두 번째 피연산자 반환)
console.log(false && "Hello"); // false (첫 번째 피연산자 반환)
console.log(true || "Hello"); // true (첫 번째 피연산자 반환)
console.log(false || "Hello"); // "Hello" (두 번째 피연산자 반환)
// 실용적 사용법
const name = user && user.name; // user가 존재하면 user.name, 아니면 undefined
const defaultName = userName || "게스트"; // userName이 truthy면 그 값, 아니면 "게스트"
5. 삼항 연산자
삼항 연산자는 조건에 따라 두 값 중 하나를 반환하는 간단한 조건 연산자입니다.
문법: 조건 ? 참일 때 값 : 거짓일 때 값
// 삼항 연산자 예제
const age = 20;
const status = age >= 18 ? "성인" : "미성년자";
console.log(status); // "성인"
// if문 대체
const score = 85;
const grade = score >= 90 ? "A" :
score >= 80 ? "B" :
score >= 70 ? "C" :
score >= 60 ? "D" : "F";
console.log(grade); // "B"
// JSX나 템플릿에서 조건부 렌더링
const message = isLoggedIn ? `안녕하세요, ${userName}!` : "로그인이 필요합니다.";
// 삼항 연산자와 || 연산자 함께 사용
const greeting = isMorning ? "좋은 아침" : (isEvening ? "좋은 저녁" : "안녕하세요");
6. 기타 연산자
typeof 연산자
변수나 값의 데이터 타입을 문자열로 반환합니다.
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (JavaScript의 유명한 버그)
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function(){}); // "function"
instanceof 연산자
객체가 특정 생성자의 인스턴스인지 확인합니다.
const arr = [1, 2, 3];
const obj = { name: "홍길동" };
const date = new Date();
console.log(arr instanceof Array); // true
console.log(obj instanceof Object); // true
console.log(date instanceof Date); // true
console.log(arr instanceof Object); // true (Array는 Object를 상속)
console.log("문자열" instanceof String); // false (원시값은 객체가 아님)
전개 연산자(Spread Operator) - ES6
배열이나 객체의 요소를 개별 요소로 확장합니다.
// 배열 복사 및 병합
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
// 객체 복사 및 병합
const obj1 = { name: "홍길동", age: 25 };
const obj2 = { ...obj1, job: "개발자" }; // { name: "홍길동", age: 25, job: "개발자" }
// 함수 인자로 사용
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6
// 배열 요소 분해
const [first, ...rest] = [1, 2, 3, 4];
console.log(first, rest); // 1, [2, 3, 4]
옵셔널 체이닝 연산자(Optional Chaining) - ES2020
객체의 속성이 undefined나 null인 경우 에러 없이 undefined를 반환합니다.
const user = {
profile: {
name: "홍길동"
// address는 정의되지 않음
}
};
// 이전 방식
const city1 = user.profile && user.profile.address && user.profile.address.city;
// 옵셔널 체이닝 사용
const city2 = user.profile?.address?.city;
console.log(city2); // undefined (에러 발생하지 않음)
// 메서드 호출에도 사용 가능
const result = user.getData?.(); // getData 메서드가 없으면 undefined
Nullish 병합 연산자(Nullish Coalescing) - ES2020
왼쪽 피연산자가 null이나 undefined일 때만 오른쪽 피연산자를 반환합니다.
// || 연산자는 falsy 값(0, "", false 등)도 오른쪽 값으로 대체
const count = 0 || 10; // 10
// ?? 연산자는 null과 undefined만 오른쪽 값으로 대체
const count2 = 0 ?? 10; // 0
const name = null ?? "익명"; // "익명"
const message = undefined ?? "메시지 없음"; // "메시지 없음"
연산자 우선순위
연산자에는 우선순위가 있어 여러 연산자가 함께 사용될 때 어떤 순서로 실행될지 결정합니다. 괄호 ()를 사용하면 우선순위를 명시적으로 지정할 수 있습니다.
// 우선순위 예제
console.log(3 + 4 * 5); // 23 (곱셈이 먼저 실행)
console.log((3 + 4) * 5); // 35 (괄호 내부가 먼저 실행)
// 복잡한 표현식
console.log(2 + 3 > 1 * 5 && !(10 % 3 === 0)); // false
// 명확성을 위해 괄호 사용 권장
console.log(((2 + 3) > (1 * 5)) && (!(10 % 3 === 0))); // false
주요 연산자 우선순위(높은 것부터):
- 괄호 ()
- 단항 연산자(++, --, !, typeof 등)
- 산술 연산자(*, /, % 다음에 +, -)
- 비교 연산자(>, <, >=, <=, ==, === 등)
- 논리 연산자(&& 다음에 ||)
- 조건(삼항) 연산자(? :)
- 할당 연산자(=, +=, -= 등)
연산자 사용 팁
가독성을 위해 괄호 사용하기
let result = (a + b) * c / (d - e);
단축 평가 활용하기
const userDisplay = user && user.name || "게스트";
구조 분해 할당으로 코드 간결하게 만들기
const { name, age } = person;
옵셔널 체이닝과 Nullish 병합 연산자 활용하기
const settings = userSettings?.theme ?? "기본 테마";
비교 연산자 사용 시 타입 주의하기
// 느슨한 비교보다는 엄격한 비교 권장
if (value === 0) { ... }
연산자를 이해하고 올바르게 사용하면 JavaScript 코드를 더 효율적이고 간결하게 작성할 수 있습니다.