본문 바로가기
JavaScript/드림코딩 엘리 - 자바스크립트 기초 강의 (ES5+)

드림코딩 엘리 - 자바스크립트 기초 강의(ES5+) (4편)

by 정ㅇr 2021. 11. 11.
728x90

3편에 관한 보충 설명 (변수, 객체에 관해서)

// Variable, rw(read/write)
// Constant, r(read only)

// primitive type : 메모리에 값이 그대로 저장됨
// object type : 객체를 가리키는 reference 값이 메모리에 저장됨

// Note!
// Immutable data types : primitive types, frozen objects ( i.e. ojbect.freeze())
// Mutable data types : all object by default are mutable in JS
// 기본적으로 JS의 모든 객체는 값이 변경될 수 있는 mutable data type으로 본다.

Operators, Numeric Operators, Increment and decrement operators, Assignment operators, Comparison operators

연산자, 수학적 연산자, 증가 연산자, 감소 연산자, 할당 연산자, 비교 연산자

// operators (연산자)
// 1. String concatenation
console.log('my' + 'cat'); // mycat
console.log('1' + 2); // 12
console.log(`string literals: 1 + 2 = ${1+2}`);

// 2. Numeric operators
console.log(1 + 1); // add
console.log(1 - 1); // subtract
console.log(1 / 1); // divide
console.log(1 * 1); // multiply
console.log(5 % 2); // remainder
console.log(2 ** 3); // exponentiation

// 3. Increment and decrement operators
// 1) Increment
let counter = 2;
const preIncrement = ++counter;
// 값을 할당하면서 counter를 증가시킴

// counter = counter + 1;
// preIncrement = counter;
console.log(`preIncrement: ${preIncrement}, counter: ${counter}`);

const postIncrement = counter++;
// 값을 먼저 할당한 다음에 counter를 증가시킴

// postIncrement = counter;
// counter = counter + 1;
console.log(`postIncrement: ${postIncrement}, counter: ${counter}`);

// 2) Decrement
// Increment와 동작 방식이 같음
const preDecrement = --counter;
console.log(`preDecrement: ${preDecrement}, counter: ${counter}`);

const postDecrement = counter--;
console.log(`postDecrement: ${postDecrement}, counter: ${counter}`);


// 4. Assignment operators
let x = 3;
let y = 6;
x += y; // x = x + y;
x -= y;
x *= y;
x /= y;

// 5. 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

 

Logical operators (논리 연산자)

// 6. Logical operators : || (or), && (and), ! (not)
const value1 = true;
const value2 = 4 < 2;

// || (or), finds the first truthy value
console.log(`or: ${value1 || value2 || check()}`);
function check() {
    for (let i = 0; i < 10; i++) {
        // wasting time
        console.log('oh.. no..');
    }
    return true;
}

// && (and), finds the first falsy vlaue
console.log(`or: ${value1 && value2 && check()}`);

or 연산자는 맨 처음 값이 true가 되면 뒤에 값들은 실행이 안된다.

그러므로, 코드를 작성할 때 맨 처음에 check()와 같은 함수나 표현식이 맨 앞으로 와 있으면 좋지 않다.

and 연산자도 맨 처음 값이 false가 되면 뒤에 있는 값들은 실행이 안되기 때문에, 무거운 함수나 표현식이 뒤로 가게 작성하는게 좋다.

 

! (not) 연산자

// ! (not)
const value1 = true;
console.log(!value1); // true -> false로 변환해서 출력

Equality (비교 연산자)

// 7. Equality
const stringFive = '5';
const numberFive = 5;

// == loose equality, with type conversion
// JS가 타입변환을 해서 같은 값이라고 봄
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

// object equality by reference
const ellie1 = { name: 'ellie' };
const ellie2 = { name: 'ellie' };
const ellie3 = ellie1;
console.log(ellie1 ==  ellie2); // false (reference가 달라서)
console.log(ellie1 === ellie2); // false (타입에 상관없이 reference가 달라서)
console.log(ellie1 === ellie3); // true (ellie1을 할당한 값이기 때문에)
// equality - puzzler
console.log(0 == false); // true
console.log(0 === false); // false (boolean type이 아님)
console.log('' == false); // true
console.log('' === false); // false (boolean type이 아님)
console.log(null == undefined); // true
console.log(null === undefined); // false

퀴즈 다 맞췄다 히히

 

Conditional operators (조건문), Ternary operators (삼항 연산자), Switch operators (Switch문)

// 8. Conditional operators: if
// if, else if, else
const name = 'df';
if (name === 'ellie') {
    console.log('Welcome Ellie!');
} else if (name === 'coder') {
    console.log('You are amazing coder');
} else {
    console.log('unknown');
}

// 9. Ternary operator: ? 삼항 연산자
// condition ? value1 : value2;
console.log(name === 'ellie' ? 'yes' : 'no');

// 10. Switch statement
// use for multiple if checks
// use for enum-like value check
// use for nultiple type checks in TS
const browser = 'IE';
switch (browser) {
    case 'IE':
        console.log('go away!');
        break;
    case 'Chrome':
    case 'Firefox':
        console.log('love you!');
    default:
        console.log('same all!');
        break;
}

Loops (반복문)

// 11. Loops
// while loop, while the condition is truthy,
// body code is executed.
let i = 3;
while (i > 0) {
    console.log(`while: ${i}`);
    i--;
}

// do while loop, body code is executed first,
// then check the condition.
do {
    console.log(`do while: ${i}`);
    i--;
} while (i > 0);
// for loop, for(begin; condition; step)
for (i = 3; i > 0; i--) {
    console.log(`for: ${i}`);
}

for ( let i = 3; i > 0; i = i - 2) {
    // inline variable declaration
    // for문 안에 지역변수를 선언해서 사용하는 경우
    console.log(`inline variable for: ${i}`);
}

// nested loops
// nesting 해서 이와 같이 for 문을 작성하는 것은 CPU에 좋지 않음
for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
        console.log(`i: ${i}, j:${j}`);
    }
}

퀴즈

// break, continue
// Q1. iterate from 0 to 10 and print only even numbers (use continue)
for (let i = 0; i < 11; i++) {
    if (i % 2 !== 0) {
        continue;
    }
    console.log(`q1. ${i}`);
}

// Q2. iterate from 0 to 10 and print numbers until reaching 8 (use break)
for (let i = 0; i < 9; i++) {
    if (i > 8) {
        break;
    }
    console.log(`q2. ${i}`);
}

 


출처

https://www.youtube.com/watch?v=YBjufjBaxHo&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=4&ab_channel=%EB%93%9C%EB%A6%BC%EC%BD%94%EB%94%A9by%EC%97%98%EB%A6%AC

반응형

댓글