본문 바로가기
웹/JavaScript

JavaScript 심화

by 코낄2 2023. 11. 6.

1. 기본 타입(Primitive Type)과 객체(Object Type)

기본 타입(Primitive Type)
   - 기본 타입은 값 자체를 저장하며, 불변(immutable)입니다. 이는 변수에 할당된 값이 변경되지 않는다는 의미입니다.
   - 주요 기본 타입: string, number, boolean, undefined, symbol, null, bigint
객체(Object Type)
   - 객체는 여러 속성과 메서드를 포함하는 복합 데이터 구조입니다. 이러한 속성은 키-값 쌍(key-value pairs)으로 구성됩니다.
   - 객체는 가변(mutable)하며, 속성을 추가, 수정, 삭제할 수 있습니다.
[차이점]
- 기본 타입은 값을 직접 저장하고 복사할 때 값 자체가 복사됩니다. 객체는 참조(reference)로 저장되므로 변수에 할당된 값은 해당 객체를 가리키는 메모리 위치입니다. 따라서 객체를 복사하면 두 변수가 동일한 객체를 참조합니다.
- 기본 타입은 불변하며 변경할 수 없지만, 객체는 속성을 동적으로 추가, 수정 및 삭제할 수 있습니다.
- 기본 타입은 비교 시 값 비교가 이루어지고, 객체는 참조 비교가 이루어집니다.


2. 동등 연산자(===)

- 기본 타입으로 생성된 변수와 new 키워드를 사용하여 명시적으로 생성된 래퍼 객체는 서로 타입이 다름

    'JavaScript' === 'JavaScript'   // true
    'JavaScript' === new String('JavaScript')  // false
    
    let num1 = 10
    let num2 = new Number(10)
    num1 === num2 // false


하지만 래퍼 객체는 메모리 사용량과 성능에 영향을 미칠 수 있어 기본 타입 값을 직접 사용하는 것이 더 효율적이며 코드를 간결하게 유지하는 데 도움이 됩니다.

3. 이터레이터(Iterator) & 이터러블(Iterable)

자바스크립트에서 이터레이터(Iterator) 객체는 특정 객체에 대해 순회 가능한 인터페이스를 제공하는 객체입니다. 이터레이터 객체는 next() 메서드를 통해 순회를 수행하며, 각 순회 단계에서는 현재 값(value)과 순회의 종료 여부(done)를 반환합니다. 

const arr = [1, 2, 3, 4, 5];
        console.log(arr.values())     // Array Iterator{}
        console.log(arr.entries())    // Array Iterator{}
        console.log(arr.keys())       // Array Iterator{}

        const iterator = arr.values();
        while(true){
            const item = iterator.next();
            console.log(item);    // {value: 1, done: false}
            break
        }
        const arr = [1, 2, 3, 4, 5];
        const iterator = arr.values();
        while(true){
            const item = iterator.next();
            if(item.done) break;
            console.log(item.value);  // 1 2 3 4 5
        }

        for(let item of arr){
            console.log(item)   // 1 2 3 4 5
        }

이터러블(Iterable) 객체는 순회 가능한 객체를 나타냅니다. 이는 객체가 내부적으로 [Symbol.iterator] 메서드를 구현하고 있어서 순회 가능한 것을 의미합니다. 예를 들어, 배열, 문자열, 맵(Map), 셋(Set)과 같은 자료구조들은 기본적으로 이터러블 객체입니다. 이터러블 객체는 for...of 루프와 같은 구조에서 직접 사용할 수 있습니다.

        function iter(){
            let index = 0;
            let data = [1,2,3,4];
            return {
                next(){
                    if(index < data.length){
                        return {value:data[index++], done:false}
                    }else{
                        return {value:undefined, done: true}
                    }
                }
            }
        }

        let i = iter();
        console.log(i.next())   // {value: 1, done: false}
        console.log(i.next())   // {value: 2, done: false}
        console.log(i.next())   // {value: 3, done: false}
        console.log(i.next())   // {value: 4, done: false}
        console.log(i.next())   // {value: undefined, done: true}

4. 스프레드(Spread) 연산자

스프레드(Spread) 연산자는 주로 배열이나 객체를 펼쳐서 각 요소 또는 속성을 개별적으로 사용할 수 있게 해줍니다. 모든 Iterable은 spread가 될 수 있습니다. 순회가 가능한 데이터는 펼쳐 질 수 있습니다.

        function add(num1, num2, num3){
            return num1 + num2 + num3;
        }

        const nums = [10, 20, 30];
        console.log(add(...nums)) // nums를 복사해서 펼쳐 넣는다.
        // 60
        const apple = {name:'김사과', age: 20, address: {si: '서울시', gu:'강남구'}}
        const apple_update = {...apple, job:'프로그래머'}
        
        console.log(apple_update)
        // {name: '김사과', age: 20, address: {…}, job: '프로그래머'}
        console.log(apple)
        // {name: '김사과', age: 20, address: {…}}

^ 새로 복사 후 펼쳐놓기 떄문에 apple 객체의 값은 그대로입니다. 스프레드 연산자는 불변성(immutable)을 유지하면서 데이터를 조작하는 데 유용하며, 코드의 가독성을 높여주는 역할을 합니다.

function sum(num1, num2, ...nums) {
  console.log(nums);
}

sum(10, 20, 30, 40, 50);
// 출력: [30, 40, 50]

^ 나머지 매개변수 문법 : 함수에 전달된 모든 나머지 인자를 배열로 받아들인다.

        const fruits = ['🍎','🍒','🍌','🍋']
        const [fruit1, fruit2, ...others] = fruits;
        console.log(fruit1) // 🍎
        console.log(fruit2) // 🍒
        console.log(others) // ['🍌', '🍋']
        const fruits1 = ['🍎','🍒']
        const fruits2 = ['🍌','🍋']
        let arr = fruits1.concat(fruits2);
        console.log(arr);   // ['🍎', '🍒', '🍌', '🍋']
        arr = [...fruits1, ...fruits2];
        console.log(arr);   // ['🍎', '🍒', '🍌', '🍋']
        arr = [...fruits1, '🍉', ...fruits2];
        console.log(arr);   // ['🍎', '🍒', '🍉', '🍌', '🍋']
        const apple = {name:'김사과', age: 20,job:'프로그래머' }

        function display({name, age, job}){
            console.log('이름', name);
            console.log('나이', age);
            console.log('직업', job);
        }

        display(apple)
         =>이름 김사과
           나이 20
           직업 프로그래머
const {name,age,pet='루시',job:hobby} = apple;
        console.log('이름', name);  // 이름 김사과
        console.log('나이', age);   // 나이 20
        console.log('펫', pet);     // 펫 루시
        console.log('직업', hobby); // job이름을 hobby로 넣어줌 // 직업 프로그래머
        const component = {
            name: 'Button',
            styles: {
                size: 20,
                color: 'black'
            }
        }

        function changeColor({styles:{color}}){
            console.log(color)
        }   // black 출력

' > JavaScript' 카테고리의 다른 글

이벤트(Event)  (0) 2023.10.30
정규 표현식  (1) 2023.10.29
Node 메서드  (0) 2023.10.29
Form객체/Document 객체 등  (1) 2023.10.29
Interval, Timeout 함수  (0) 2023.10.28