자바스크립트의 연산자

자바스크립트의 연산자

이 기사에서는 자바스크립트에서 사용되는 연산자들을 설명하겠습니다.

YouTube Video

자바스크립트의 연산자

자바스크립트의 연산자는 숫자와 변수의 계산 및 비교를 수행하기 위해 사용되는 기호 또는 키워드입니다. 각기 다른 연산을 수행하는 다양한 종류의 연산자가 존재합니다. 주요 연산자들에 대해 간략히 정리해 보겠습니다:.

산술 연산자

JavaScript의 산술 연산자에는 다음이 포함됩니다:.

연산자 설명 예제 결과
+ 덧셈 5 + 2 7
- 뺄셈 5 - 2 3
* 곱셈 5 * 2 10
/ 나눗셈 5 / 2 2.5
% 나머지 (모듈러스) 5 % 2 1
++ 증가 (1씩 증가) let x = 5; x++ 6
-- 감소 (1씩 감소) let x = 5; x-- 4
 1let a = 10; // Initialize variable 'a' with the value 10
 2let b = 3;  // Initialize variable 'b' with the value 3
 3
 4// Perform and display arithmetic operations between 'a' and 'b'
 5console.log("Addition (a + b):      ", a + b); // 13
 6console.log("Subtraction (a - b):   ", a - b); // 7
 7console.log("Multiplication (a * b):", a * b); // 30
 8console.log("Division (a / b):      ", a / b); // 3.333...
 9console.log("Modulus (a % b):       ", a % b); // 1
10
11// Demonstrate post-increment operation on 'a'
12// Output the current value of 'a' (10), then increment
13console.log("Post-increment (a++):  ", a++);
14// Display the incremented value of 'a' (11)
15console.log("Value of 'a' after increment:", a);
16
17// Demonstrate pre-increment operation on 'a'
18// Increment 'a' first (12) then output
19console.log("Pre-increment (++a):   ", ++a);
20
21// Demonstrate post-decrement operation on 'a'
22// Output the current value of 'a' (12), then decrement
23console.log("Post-decrement (a--):  ", a--);
24// Display the decremented value of 'a' (11)
25console.log("Value of 'a' after decrement:", a);
26
27// Demonstrate pre-decrement operation on 'a'
28// Decrement 'a' first (10) then output
29console.log("Pre-decrement (--a):   ", --a);

산술 연산자는 숫자에 대해 기본적인 수학 연산을 수행합니다. 덧셈과 뺄셈 이외에도 모듈러스, 증가, 감소와 같은 연산을 수행할 수 있습니다. 증가 또는 감소 연산자가 피연산자 앞에 있는지 뒤에 있는지에 따라 반환되는 값이 달라진다는 점에 유의하세요.

할당 연산자

JavaScript의 할당 연산자에는 다음이 포함됩니다:.

연산자 설명 예제 결과
= 할당 x = 5 x에 값 5를 할당합니다.
+= 덧셈 할당 x += 5 x = x + 5
-= 뺄셈 할당 x -= 5 x = x - 5
*= 곱셈 할당 x *= 5 x = x * 5
/= 나눗셈 할당 x /= 5 x = x / 5
%= 나머지 할당 x %= 5 x = x % 5
 1let x = 10;
 2
 3x += 5;  // x = x + 5, so x becomes 15
 4console.log('After x += 5 : ', x);  // 15
 5
 6x -= 10;
 7console.log('After x -= 10 : ', x);  // 5
 8
 9x *= 3;
10console.log('After x *= 3 : ', x);  // 15
11
12x /= 3;
13console.log('After x /= 3 : ', x);  // 5
14
15x %= 2;
16console.log('After x %= 2 : ', x);  // 1

할당 연산자는 변수에 값을 할당하거나 변수의 값을 업데이트하는 데 사용됩니다. 일반 할당 외에도 덧셈 및 나머지와 같은 산술 연산을 위한 할당 연산자가 있습니다.

비교 연산자

JavaScript의 비교 연산자에는 다음이 포함됩니다:.

연산자 설명 예제 결과
== 같음 5 == "5" true
=== 엄격하게 같음 (타입과 값이 모두 같음) 5 === "5" false
!= 같지 않음 5 != "5" false
!== 엄격하게 같지 않음 5 !== "5" true
> 크다 5 > 2 true
< 작다 5 < 2 false
>= 크거나 같다 5 >= 5 true
<= 작거나 같다 5 <= 4 false
 1console.log("5 == '5' evaluates to:", 5 == "5");   // true (because the values are equal)
 2console.log("5 === '5' evaluates to:", 5 === "5"); // false (because the types are different)
 3console.log("5 != '5' evaluates to:", 5 != "5");   // false
 4console.log("5 !== '5' evaluates to:", 5 !== "5"); // true
 5console.log("5 > 2 evaluates to:", 5 > 2);         // true
 6console.log("5 < 2 evaluates to:", 5 < 2);         // false
 7console.log("5 >= 5 evaluates to:", 5 >= 5);       // true
 8console.log("5 <= 4 evaluates to:", 5 <= 4);       // false
 9console.log("5 >= '5' evaluates to:", 5 >= "5");   // true
10console.log("5 <= '5' evaluates to:", 5 <= "5");   // true
  • 비교 연산자는 값을 비교하고 true 또는 false를 반환합니다.
  • 동등 연산자 (==)는 비교를 수행하기 전에 필요한 경우 서로 다른 유형을 자동으로 변환합니다. 엄격한 동등 연산자 (===)는 비교 중에 어떤 유형 변환도 수행하지 않으며, 두 값이 동일한 유형이고 동일한 값일 경우에만 true를 반환합니다. 엄격한 동등 연산자 (===)를 사용하면 의도하지 않은 유형 변환으로 인한 버그를 방지할 수 있으므로 우선적으로 사용하는 것이 권장됩니다.

논리 연산자

JavaScript의 논리 연산자에는 다음이 포함됩니다:.

연산자 설명 예제 결과
&& AND (두 조건이 모두 true일 때 true) true && false false
|| OR (조건 중 하나라도 true일 때 true) true || false true
! NOT (true를 false로, false를 true로 변환) !true false
1let a = true;
2let b = false;
3
4console.log("a && b evaluates to:", a && b);  // false
5console.log("a || b evaluates to:", a || b);  // true
6console.log("!a evaluates to:", !a);          // false

논리 연산자는 여러 조건이 있을 때 조건의 조합을 평가하는 데 사용됩니다.

논리 연산자의 우선순위

JavaScript에서는 논리 연산자가 일반적으로 NOT, AND, OR 순서로 평가됩니다.

NOT이 가장 높은 우선순위를 가집니다

NOT은 단항 연산자로 가장 높은 우선순위를 가지고 평가됩니다.

1console.log(!true || false);  // false
ANDOR보다 높은 우선순위를 가집니다

ANDOR보다 높은 우선순위를 가지므로 AND 부분이 먼저 평가됩니다.

1console.log(true || false && false);  // true

이와 같이, AND (&&) 부분이 먼저 평가되고 그 결과가 OR (||)에 전달됩니다.

ANDOR은 단락 평가를 수행합니다

JavaScript의 ANDOR은 단락 평가를 수행합니다. 왼쪽 값만으로 결과가 결정될 수 있는 경우, 오른쪽 표현식은 평가되지 않습니다.

1let a = false && console.log("This will not be printed");
2console.log(a);  // false
3
4let b = true || console.log("This will not be printed");
5console.log(b);  // true

어느 경우든, console.log()는 실행되지 않습니다.

명시적으로 우선순위를 설정하십시오

괄호로 표현식을 명시적으로 그룹화하면, 연산자 우선순위에 대한 오해를 방지할 수 있습니다.

1console.log(true || (false && false));  // true
자연어와 프로그래밍 해석의 차이점

논리 연산자를 사용할 때, 자연어의 모호성에 유의하는 것이 중요합니다. 예를 들어, '흰 개 또는 고양이'라고 말할 때, 이는 '흰 개 또는 어떤 색의 고양이' 또는 '흰 개 또는 흰 고양이'를 의미할 수 있습니다. 코드에서는 다음과 같이 표현될 수 있습니다:.

1if (isWhite && isDog || isCat) {
2    console.log(' "A white dog" or "a cat of any color" ');
3}
4
5if (isWhite && (isDog || isCat)) {
6    console.log(' "A white dog" or "a white cat" ');
7}
8
9console.log(true || (false && false));  // true

자연어는 이와 같은 모호성을 포함하기 때문에, 코딩이나 설계를 할 때 주의가 필요합니다.

삼항 연산자 (조건 연산자)

JavaScript에는 **삼항 연산자(조건 연산자)**가 포함됩니다.

연산자 설명 예제 결과
? : 조건이 true일 경우 왼쪽이 실행되고, false일 경우 오른쪽이 실행됩니다 condition ? if true : if false 조건에 따른 결과
1let age = 20;
2let message = age >= 18 ? "Adult" : "Minor";
3console.log(message);  // "Adult"

condition ? 참일 때의 값 : 거짓일 때의 값 형태로 작성됩니다.

비트 연산자

JavaScript 비트 연산자에는 다음이 포함됩니다.

연산자 설명 예제 결과
& AND 5 & 1 1
| OR 5 | 1 5
^ XOR 5 ^ 1 4
~ NOT ~5 -6
<< 왼쪽 시프트 5 << 1 10
>> 오른쪽 시프트 5 >> 1 2
 1let x = 0x0F & 0x0C;
 2console.log("0x0F & 0x0C evaluates to:", x, "(0x0C, 12)");  // 0x0C (12)
 3
 4x = 0x04 | 0x02;
 5console.log("0x04 | 0x02 evaluates to:", x, "(0x06, 6)");  // 0x06 (6)
 6
 7x = 0x0F ^ 0x0C;
 8console.log("0x0F ^ 0x0C evaluates to:", x, "(0x03, 3)");  // 0x03 (3)
 9
10// The inverted number is represented as a negative value
11// because JavaScript numbers are stored as signed 32-bit integers.
12x = ~0x0C;
13console.log("~0x0C evaluates to:", x, "(-13, 0xF3)");  // 0xF3 (-13)
14
15x = 0x04 << 1;
16console.log("0x04 << 1 evaluates to:", x, "(0x08, 8)");    // 0x08 (8)
17x = 0x04 >> 1;
18console.log("0x04 >> 1 evaluates to:", x, "(0x02, 2)");    // 0x02 (2)

비트 연산자는 숫자를 비트 수준에서 계산합니다. 일반적으로 저수준 처리를 위해 사용됩니다.

타입 연산자

JavaScript 타입 연산자에는 다음이 포함됩니다.

연산자 설명 예제 결과
typeof 변수의 타입을 반환합니다 typeof 123 "number"
instanceof 객체가 특정 클래스에 속해 있는지 확인합니다 arr instanceof Array true
1console.log(typeof "Hello");  // "string"
2console.log(typeof 42);       // "number"
3
4let arr = [1, 2, 3];
5console.log("arr instanceof Array : ", arr instanceof Array); // true

타입 연산자는 값의 타입을 확인하거나 특정 타입으로 변환하는 데 사용됩니다.

typeof 연산자는 변수의 타입을 반환합니다.

instanceof 연산자는 객체가 특정 클래스에 속하는지 확인합니다.

요약

  • 산술 연산자는 기본 계산을 수행합니다.
  • 할당 연산자는 변수에 값을 할당하거나 업데이트합니다.
  • 비교 연산자는 두 값을 비교하고 true 또는 false를 반환합니다.
  • 논리 연산자는 조건의 조합을 평가합니다.
  • 삼항 연산자if보다 짧은 문법으로 조건문을 작성할 수 있게 해줍니다.
  • 비트 연산자는 비트 수준에서 계산을 수행합니다.
  • 타입 연산자는 값의 타입을 확인할 수 있게 해줍니다.

위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.

YouTube Video