반응형
연산자
어떠한 연산을 수행하는 기호입니다.
문자열 병합
- 문자열은 + 연산자를 사용하여 병합할 수 있습니다.
//javascript
console.log("안녕" + "하세요"); // "안녕하세요" 출력
console.log("1" + 2 + 3); // "123" 출력
산술 연산자
- x + y - 덧셈
- x - y - 뺄셈
- x * y - 곱셈
- x / y - 나눗셈
- x % y - 나머지
//javascript
let x = 10;
let y = 20;
console.log(x + y);
console.log(x - y);
console.log(x * y);
console.log(x / y);
console.log(9 % 2);
증감 연산자
- ++x - 전위 증가 (x에 1만큼 증가 시킨 후 현재 명령문 수행)
- x++ - 후위 증가 (현재 명령문 수행 후 x에 1 증가)
- --x - 전위 감소 (x에 1만큼 감소 시킨 후 현재 명령문 수행)
- x-- - 후위 감소 (현재 명령문 수행 후 x에 1 감소)
//javascript
let x = 10;
let y = 20;
let result = ++x + y;
console.log(result);
console.log(x);
console.log(y);
비교 연산자
값을 서로 비교하고 참인지에 따라 논리 값을 반환합니다.
- a > b - a가 b보다 크다.
- a < b - a가 b보다 작다.
- a >= b - a가 b보다 크거나 같다.
- a <= b - a가 b보다 작거나 같다.
- a == b - a와 b는 같다.
- a === b - a와 b는 같다.(데이터 타입 까지)
- a != b - a와 b는 같지않다.
- a !== b - a와 b는 같지않다.(데이터 타입 까지)
//javascript
let a = 2;
let b = 2;
console.log(a > b);
console.log(a == b); // true
console.log(a != b); // false
// b를 문자열로 바꾸면
console.log(a === b); // false
console.log(a !== b); // true
할당 연산자
- x += y - x = x + y와 같다.
- x -= y - x = x - y와 같다.
- x *= y - x = x * y와 같다.
- x /= y - x = x / y와 같다.
//javascript
let x = 10;
let y = 20;
// x = x + y;
x += y;
console.log(x);
논리 연산자
- 논리 연산자는 boolean값만 다룰 수 있지만 자바스크립트에서는 모든 타입의 값을 받을 수 있고 연산 결과 역시 모든 타입이 될 수 있습니다.
- null, 0, NaN, 빈 문자열(""), undefined 값은 false로 간주됩니다.
1. AND 연산 (&&)
- 피연산자가 모두 true일 경우에 true를 반환하고 나머지는 false를 반환합니다.
//javascript
let a1 = true && true; // t && t returns true
let a2 = true && false; // t && f returns false
let a3 = false && true; // f && t returns false
let a4 = false && (3 == 4); // f && f returns false
let a5 = 111 && 222; // t && t returns 222
let a6 = false && 222; // f && t returns false
let a7 = 111 && false; // t && f returns false
let a8 = undefined && null; // f && f returns undefined
console.log(a1);
2. OR 연산 (||)
- 피연산자 중 하나라도 true이면 true를 반환하고 나머지는 false를 반환합니다.
//javascript
let o1 = true || true; // t || t returns true
let o2 = false || true; // f || t returns true
let o3 = true || false; // t || f returns true
let o4 = false || (3 == 4); // f || f returns false
let o5 = 111 || 222; // t || t returns 111
let o6 = false || 222; // f || t returns 222
let o7 = 111 || false; // t || f returns 111
let o8 = undefined || null; // f && f returns null
console.log(o1);
3. NOT 연산 (!)
- true이면 false, false 일 경우 true를 반환합니다.
//javascript
let n1 = !true; // !t returns false
let n2 = !false; // !f returns true
let n3 = !111; // !t returns false
삼항 연산자
- 조건식 ? 값1 : 값2 - 조건식이 true 이면 값1을 반환하고, false 이면 값2를 반환합니다.
//javascript
let number = 21;
let result = number % 2 == 1 ? "홀수입니다." : "짝수입니다.";
console.log(result);
반응형
'JavaScript' 카테고리의 다른 글
| 6. 조건문 (0) | 2024.05.10 |
|---|---|
| 5. 배열 (0) | 2024.05.06 |
| 3. 자료형 (0) | 2024.05.02 |
| 2. 변수, 상수 (0) | 2024.04.30 |
| 1. javascript 시작하기 (0) | 2024.04.29 |