Operator(연산자)는 프로그래밍에서 사용하는 기호라고 합니다. 연산자에는 문자열 연산자, 산술 연산자, 논리 연산자 등등이 있습니다. (드림코딩 영상에서 배운 것을 토대로 작성하기 때문에 MDN이나 다른 사이트에서 알려주는 용어와 다를 수 있습니다.)
글 작성 시 제로초님의 글과 MDN사이트의 글을 참고하여 작성했습니다.
String concatenation(문자열 연결 연산자)는 +입니다. 이는 두 문자열 값을 연결하고 , 두 문자열이 합쳐진 값을 반환합니다. 문자열이 아닌 값와 연결하는 경우 모든 값들이 문자열로 바뀌어 더해집니다.
console.log('my' + 'cat'); //출력: mycat
console.log('1' + 2); // 숫자 2가 문자로 자동 변환되어져 연결됩니다.
//출력: 12
console.log(3 + 4 + 'wow'); // 먼저 숫자끼리 더해지고 그 다음 문자열을 만나 자동 변환되어져 연결되기 때문에 34wow가 아니라 7wow로 출력됩니다.
//출력: 7wow
console.log(`string literals: 1 + 2 = ${1+2}`); //템플릿 리터럴이라고 합니다.
//${}
Template literals(템플릿 리터럴)은 자바스크립트에서 편하게 문자열을 표현할 수 있는 방식입니다. 일반적인 문자열 표현 방식과 달리 백틱(%%
)을 사용합니다. 또한 중간에 표현식을 넣고 싶다면 ${}안에 넣으면 됩니다.
var a = 5;
var b = 10;
//아래는 큰따옴표을 사용해 표현한 문자열입니다.
console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + ".");
// "Fifteen is 15 and
// not 20."
//아래는 백틱을 사용해 템플릿 리터럴로 표현한 문자열입니다.
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20."
Numeric operators(산술 연산자)는 숫자값을 피연산자로 받고 하나의 값을 반환합니다. 기본적으로 우리가 알고 있는 연산자가 여기에 해당됩니다. 그리고 특별히 프로그래밍에서는 나머지와 제곱의 연산자도 있습니다.
console.log(1 + 1); // add
//출력: 2
console.log(1 - 1); // substract
//출력: 0
console.log(1 / 1); // divide
//출력: 1
console.log(1 * 1); // multiply
//출력: 1
console.log(5 % 2); // remainder
//출력: 1
console.log(2 ** 3); // exponetiation
//출력: 8
Increment and decrement operators(감소 및 증가 연산자)는 항이 하나만 있는 단항 연산자입니다. 피연산자 앞이나 뒤에 ++ 혹은 --를 붙여 표현합니다. 이때 어디에 연산자가 붙었는지에 따라 연산 순서가 달라집니다. 앞에 있다면 연산을 하고 나서 다음 스텝을 밟습니다. 그리고 뒤에 있다면 문법적인 스텝을 밟고 나서 연산을 진행합니다.
let counter = 2;
const perIncrement = ++counter; //연산을 하고 나서 대입합니다.
// 아래 두줄의 코드를 이렇게 표현할 수 있습니다.
// counter = counter + 1;
// preIncrement = counter;
console.log(`preIncrement: ${perIncrement}, counter: ${counter}`);
//출력: preIncrement: 3, counter: 3
const postIncrement = counter--; //대입을 하고 나서 연산합니다.
// 아래 두줄의 코드를 이렇게 표현할 수 있습니다.
// postIncrement = conter;
// counter = counter - 1;
console.log(`postIncrement: ${postIncrement}, counter: ${counter}`);
//출력: postIncrement: 3, counter: 2
Assigment operators(할당 연산자)는 오른쪽의 피연산자를 왼쪽 피연산자에 할당합니다. 기본적으로 할당하는 연산자는 =(등호)이라고 합니다. 그냥 우리가 아닌 일반 산술 연산자를 줄여서 표현한다고 생각하면 편합니다.
let x = 3;
let y = 6;
x += y; // x = x + y;
x -= y; // x = x - y;
x *= y; // x = x * y;
x /= y; // x = x / y;
Comparison operators(비교 연산자)는 피연산자들을 비교하고 비교에 따른 논리값을 반환합니다. 피연산자로는 숫자, 문자열, 객체 등을 사용할 수 있습니다.
console.log(10 < 6); //less than
console.log(10 <= 6); //less than or equal
console.log(10 > 6); //greater than
console.log(10 >= 6); // greater than or equal
'같다'라는 의미가 자바스크립트에서는 다양하게 사용될 수 있습니다. == (동등)와 !=(부등) 연산자는 데이터 타입이 다른 값을 비교할 때 같은 타입으로 변환하고 값을 비교합니다. 그리고 ===(일치)와 !==(불일치)는 데이터 타입이 다르다면 가차없이 불일치를 반환합니다.
const stringFive = '5';
const numberFive = 5;
// == loose equality, with type conversion
console.log(stringFive == numberFive); //출력: true
console.log(stringFive != numberFive); //출력: false
// === strict equality, no type conversion
console.log(stringFive === numberFive); //출력: false
console.log(stringFive !== numberFive); //출력: true
Logical operators(논리 연산자)는 보통 부울 값과 함께 사용되고 부울 값을 반환합니다. &&와 || 연산시 부울 값과 사용되지 않았다면 피연산자 값을 그대로 반환할 수도 있다고 합니다.
&&(논리 곱)에 대한 연산 예시입니다.
var a1 = true && true; // t && t returns true
var a2 = true && false; // t && f returns false
var a3 = false && true; // f && t returns false
var a4 = false && (3 == 4); // f && f returns false
var a5 = "Cat" && "Dog"; // t && t returns Dog
var a6 = false && "Cat"; // f && t returns false
var a7 = "Cat" && false; // t && f returns false
var a8 = true && "Cat"; // t && t returns Cat
var a9 = "Cat" && true; // t && t returns true
||(논리 합)에 대한 연산 예시입니다.
var o1 = true || true; // t || t returns true
var o2 = false || true; // f || t returns true
var o3 = true || false; // t || f returns true
var o4 = false || (3 == 4); // f || f returns false
var o5 = "Cat" || "Dog"; // t || t returns Cat
var o6 = false || "Cat"; // f || t returns Cat
var o7 = "Cat" || false; // t || f returns Cat
var o8 = true || "Cat"; // t || t returns true
var o9 = "Cat" || true; // t || t returns Cat
!(논리 부정)에 대한 연산 예시입니다.
var n1 = !true; // !t returns false
var n2 = !false; // !f returns true
var n3 = !"Cat"; // !t returns false
논리 연산자가 왼쪽에서 오른쪽으로 평가될때, 논리연산자는 다음의 규칙을 따라서 "단축 계산"으로 검사됩니다
false && anything 는 false로 단축 계산됩니다.
true || anything 는 true로 단축 계산됩니다.
Tips 그러므로 우리는 헤비한 연산이 필요한 경우는 오른쪽에 배치하는 것이 좋습니다.
const value1 = true;
const value2 = 4 < 2; //false
// || (or), finds the first truthy value
//헤비한 연산자들은 뒤에 배치하는 것이 좋다.
console.log(`or: ${value1 || value2 || check()}`);
//출력: or: true
// && (and), finds the first falsy value
console.log(`or: ${value1 && value2 && check()}`);
//출력: or: false
function check() {
for (let i = 0; i < 10; i++) {
// wasting time
console.log(`😱`);
}
return true;
}