본문 바로가기

Language & Framework/JavaScript

자바스크립트 기초. 연산자(Operator)의 종류와 활용

1. String concatenation (문자열 연결)

consol.log('yang' + 'ddoddi') // yangddoddi
consol.log('him' + 'dulda') // haimdulda
consol.log('30' + 7) // 307
consol.log(`jibe_galle: ${2+3}`) // jibe_galle: 5
                                 // `사용하면 띄어쓰기까지 모든 문자를 출력 가능
consol.log'ddoddi\'s blog') // ddoddi's blog
                            // '사용하고 싶을 경우 백슬러시 필요

\'같이 특정한 코드를 입력해야 출력 가능한 것을 이스케이프 표현이라고 한다.

\" \\ \n \t \b  
큰 따옴표 백슬래시 줄 바꿈 백스페이스  

흔히 사용할만한 표현은 이 정도이다. 전체 이스케이프 표현을 보고 싶다면 여기로.

 

 

2. Numeric operator (산술 연산자)

console.log(4 + 2); // add(덧셈)
colsole.log(5 - 1); // substract(뺄셈)
console.log(7 / 2); // divide(나눗셈)
console.log(8 * 4); // multiply(곱셈)
console.log(2 % 1); // remainder(나머지)
console.log(4 ** 2); // exponetiation(제곱)

더 이상의 자세한 설명은 생략합니다.

 

3. increment operator & decrement operator ( 증가 연산자, 감소 연산자 )

 

let ddoddi_today = 170;
let ddoddi_tomorrow = ddoddie_today++; // 또띠의 오늘 키에 170을 할당후 +1 (postincrement)
console.log(`ddoddi_today: ${ddoddi_today}, ddoddi_tomorrow: ${ddoddi_tomorrow}`);
// ddoddi_today: 170, ddoddi_tomorrow: 171

const ddoddi_tomorrow = ++ddoddie_today; // 또띠의 오늘 키에 +1을 할당 후 또띠의 내일 키에 저장한다. (preincrement)
console.log(`ddoddi_today: ${ddoddi_today}, ddoddi_tomorrow: ${ddoddi_tomorrow}`);
// ddoddi_today: 171, ddoddi_tomorrow: 171

const ddoddi_tomorrow = ddoddie_today--; // 또띠의 오늘 키에 170을 할당후 -1 (postdecrement)
console.log(`ddoddi_today: ${ddoddi_today}, ddoddi_tomorrow: ${ddoddi_tomorrow}`);
// ddoddi_today: 170, ddoddi_tomorrow: 169

const ddoddi_tomorrow = --ddoddie_today; // 또띠의 오늘 키에 -1을 할당 후 또띠의 내일 키에 저장한다. (predecrement)
console.log(`ddoddi_today: ${ddoddi_today}, ddoddi_tomorrow: ${ddoddi_tomorrow}`);
// ddoddi_today: 169, ddoddi_tomorrow: 169

위의 예시처럼 쓰는 것은 전혀 어려울 게 없는데 약간 미묘하게 헷갈리는 부분이 있다.

Let A = 5;
B = A++;
console.log( A, B );
// 6, 5

띠용~? 이런 결과값이 나오는 이유는 A가 B에 할당되는 순간 이미 B의 값이 정해졌기 때문이다.

그리고 이후 A의 값이 증가하여 6이 된다.

아리송하지만 직접 해보면 이해가 되는 것 같으면서도 약간 아리송하다. 내가 바보인가..?

 

4. Assignment operator (할당 연산자)

할당 연산자라는 말이 새롭게 느껴질 수 있는데 별 거 없다.

Let A = 10;

위의 구문에서 A에 10을 할당하고 있다는 것을 우리는 이미 잘 알고 있다. 이게 할당 연산자다.

하지만 이거 하나 써놓고 어어.. 할당 연산자 끝! 이러기는 양심이 찔리니 할당 연산자 응용도 보도록 하자.

let a = 5;
let b = 3;
a += b // a = a + b
console.log(a); // 8
a -= b // a = a - b
console.log(a); // 5
a /= b // a = a * b
console.log(a); // 15
a *= b // a = a / b
console.log(a); // 3

더 다양한 할당 연산자 응용도 가능하다. 여기를 참고하도록 하자.

 

 

5. Comparison operator (비교 연산자)

console.log(5 < 10); // false
console.log(5 <= 10); // false
console.log(5 > 10); // true
console.log(5 >= 10); // true

너무 단순해서 따로 설명할 것이 없다. 항상 equal (=)표시가 우측에 위치한다는 것만 기억하면 쉽다.

 

 

6. Lojical operator (논리 연산자)

or and not
|| && !
const x = false;
const y = 10 > 5;
const z = ''

console.log(`and: ${ x && y && z }`); // false
// x가 false이므로 x까지만 구문을 읽고 바로 false를 반환한다.
console.log(`and: ${ y && z && x }`); // ''
// z가 false이므로 z까지만 구문을 읽고 바로 ''를 반환한다.
console.log(`or: ${ y || x || z }`); // true
// y가 true이므로 y까지만 읽고 바로 true를 반환한다.
console.log(`or: ${ !x && y && || !'' }`) // true
// !(not)은 true와 false를 반대값으로 출력한다. 따라서 가장 우측까지 읽은 뒤 ''(false)의 반대값인 true 반환.

복잡할 것이 없다. 다만 중요한 것은 논리 연산자가 true, false를 반환하는 연산자라고 착각하면 안된다.

논리 연산자는 or과 and에 따라 왼쪽부터 오른쪽으로 읽으며 해당 값이 나오면 반환하는 역할을 한다.

논리 연산자에서 이렇게 중간까지만 읽고 true나 false를 만나면 값을 반환하는 것을 단축 평가라고 한다.

const value1 = "apple";
const value2 = "samsung";

console.log(`and: ${apple || samsung}`); // apple (apple은 true이기 때문에 즉시 반환)
console.log(`and: ${apple && samsung}`); // samsung (apple, samsung 모두 참이기 때문에
                                         // samsung까지 읽고 반환)

 

7. Equality operator (동등 연산자), Strict Equality operator(일치 연산자)

 

동등 연산자(==)는 타입을 모두 숫자로 변환시킨 뒤 값을 기준으로 판단한다.

일치 연산자(===)는 타입과 값이 모두 일치해야 true를 반환한다.

console.log( '10' == 10 ); // true
console.log( '10' === 10 ); // false
console.log( 'true' == true ); // true
console.log( 'true' === true ); // false
console.log( 1 == true ); // true
console.log( 1 === true ); // false
console.log( 0 == false ); // true
console.log( 0 === false ); // false
console.log( null == undefined ); // true
console.log( null === undefined ); // false

 

Object type을 비교할 경우 같은 이름의 key와 value를 가지고 있어도 실제로는 다른 값을 가지고 있는 것이기 때문에 동등 연산자와 일치 연산자 모두 false를 반환한다.

 

const apple = { product: 'smartphone' };
const samsung = { product: 'smartphone' };
const samsung_america = samsung;

console.log (apple == samsung); 
console.log (apple === samsung); // 보기에 키와 값이 같지만 실은 가르키고 있는 키와 값이 전혀 다르다.
console.log (samsung == samsung_america);
console.log (samsung === samsung_america); // samsung_america는 samsung의 키와 값을 공유하고 있다.

 

 

8. Conditional operator (조건 연산자)

if, else if, else로 이루어져 있으며 조건문을 작성할 시 if로 시작해서 else if를 모두 거친 뒤 일치하는 값을 찾아내지 못하면 else에서 값을 반환한다.

const mynotebook = 'Macbook';
if ( mynotebook === 'galaxybook' ) {
    console.log('really?');
}
else if ( mynotebook === 'vivobook') {
    console.log('Pizzubook!');
}
else if ( mynotebook === 'Macbook') {
    console.log('you can enter Starbucks');
}
else  {
    console.log('더 입력하기 귀찮다..');
};

// you can enter Starbucks

 

 

9. Ternary operator (삼항 조건 연산자)

조건문의 단축 형태로 활용 가능하다.

기본적인 형태는 조건식 ? true일 때 반환할 값 : false일 때 반환할 값

 

const notebook = 'macbook';
const enter_stabuks = notebook === 'macbook' ? ' 음료 나오면 닉네임으로 알려드릴게요. ' : ' 죄송합니다, 나가주세요.' ;

console.log(enter_stabuks); // ' 음료 나오면 닉네임으로 알려드릴게요. '

이걸 대체 어디에 쓸 수 있을 까?

 

const membership = true
const price = (membership ? '2500원' : '5000원') + '입니다!';
console.log(price); // 2500원입니다!

이런 식으로 활용 가능하다. 호호.

 

 

10. Switch statement (스위치문)

Switc 번수 = { case 변수 : 실행할 코드 }

if 조건문과의 차이

1. 비교 연산이 불가능하며 case 변수는 상수만 사용 가능하다.

2. break을 사용하지 않으면 해당 값을 반환하고 아래로 내려가며 break을 만날 때까지 모든 값을 반환한다.

const my_ranking = 7;
switch (my_ranking) {
    case 1 : console.log('100만원');
    break;
    case 2 : console.log('50만원');
    break;
    case 3 : console.log('10만원');
    break;
    default : console.log('아쉽네요');
};
// 아쉽네요

만약 break를 생략할 경우 1등이 100만원 50만원 10만원을 모두 반환하고 아쉽네요까지 반환하게 된다.

default는 마지막 조건문이므로 break를 생략해도 관계 없다.

 

 

11. Loops (반복문)

for (let ddoddis_height = 170; ddoddis_height <= 187; ddoddis_height++) {
    console.log(ddoddis_height);
} // 170 171 172 173 .. 186 187

for문은 for ( 변수 선언; 조건; 조건식)이 기본 형태이다.

 

let ddoddis_height = 187;
while (ddoddis_height >= 170) {
    console.log(ddoddis_height);
    ddoddis_height--;
} // 187 186 185 184 .. 171 170

while문은 while (조건) {조건식;}이 기본 형태이다.

주의점은 조건을 만날 때까지 계속해서 반복하기 때문에 무한대로 반복되어 에러를 뱉어내는 일이 없도록 코드를 작성해야 한다.

 

let ddoddis_height = 170
do {console.log(ddoddis_height); ddoddis_height++;} while (
    ddoddis_height < 187);

do는 while과 함께 사용하며 특징은 for문 while문과 달리 먼저 값을 반환한 뒤 조건식을 검사한다는 것이다.

그래서 do는 무조건 1개 이상의 값을 반환한다.

 

let ddoddis_height = 170

while (ddoddis_height < 190) {
    ddoddis_height++;
    if (ddoddis_height > 187) {
        break;
    }
    console.log(ddoddis_height);
} // 170 171 172 .. 186 187

while (ddoddis_height > 170) {
    ddoddis_height--;
    if (ddoddis_height%2 === 0){
        continue; // 값을 2로 나눴을 때 나머지가 0이면 값을 반환하지 않고 반복한다
    }
    console.log(ddoddis_height);
} // 187 185 183 .. 173 171

for (let ddoddis_weight = 75; ddoddis_weight > 65; ddoddis_weight--) {
    if(ddoddis_weight%2 === 1){
        continue; // 값을 2로 나눴을 때 나머지가 1이면 값을 반환하지 않고 반복한다
    }
    console.log(ddoddis_weight);
} // 74 72 70 .. 66

if를 활용하여 조건 반복문을 만들 수 있다.

continue라는 새로운 친구가 존재하는데, break는 만나면 반복을 중단해버리지만 continue는 중단하지 않고 해당 값만 반환하지 않은 뒤 반복을 조건이 끝날 때까지 다시 반복한다.

 

 

 

 

--