프로그래밍/JavaScript

[JS] 자바스크립트 기본 문법 정리

대인보우 2021. 2. 27. 14:59
반응형

변수 차이점

var 함수 스코프이기 때문에 블록 안에서 정의했어도 밖에서 사용 가능
const, let 블록 스코프를 가지므로 블록 밖에서는 접근 불가능 
코드 관리가 수월해짐

 

const const는 한번 대입하면 다른 값 대입 불가
let let은 다른 값 재할당 가능 

 

템플릿 문자열

string2 = `${num3} 더하기 ${num4}는 '${result2}'`;
# 1 더하기 2는 '3'

 

객체 리터럴

const es = 'ES' 
const newObject = {
    sayJS(){ // sayJS: function()으로 정의할 필요 없이 가능
        console.log('JS');
    },
    sayNode,
    [es + 6]: 'Fantastic', // 객체 리터럴 안에서 가능
};

console.log(newObject.ES6); // Fantastic

 

화살표 함수

function add1(x, y) {
    return x+y;
}

const add2 = (x,y) => {
    return x + y;
}

const add3 = (x,y) => x + y;

const add4 = (x, y) => (x + y);

다 같은 결과 출력 

const relationship2 = {
    name: 'zero',
    friends: ['nero', 'hero', 'xero'],
    logFriends() {
        this.friends.forEach(friend => { //this는 relationship2
            console.log(this.name, friend);
        });
    },
};
relationship2.logFriends();

 

비구조화 할당

var candyMachine = {
    status: {
        name: 'node',
        count: 5,
    },
    getCandy: function() {
        this.status.count--;
        return this.status.count;
    }
};

// 방법 1
var getCandy = candyMachine.getCandy;
var count = candyMachine.status.count;

// 방법2
const { getCandy, status: {count}} = candyMachine;

 

 

반응형