1. const, let
변수를 재선언 하는 경우 기존의 값은 삭제가 되고 새로운 값이 덮힌다.
간단한 코드가 아닌, 길고 복잡한 코드에서는 사람이기에 기존의 선언해둔 변수의 존재를 잊고 재선언하는 경우에는 문제가 발생이 될 수 있다.
이를 보완하기 위해 추가된 변수 선언 방식이 let과 const이다.
1) let
중복선언 불가, 재할당 가능
let title = 'book';
console.log(title); // book
let title = 'movie';
console.log(title);
//Uncaught SyntaxError: Identifier 'title' has already been declared
title = 'music';
console.log(title);//music
let은 var와 달리 중복선언 시, 해당 변수는 이미 선언되었다는 에러 메시지를 뱉는다.
즉, 중복선언이 불가하다. 하지만 변수에 값을 재할당하는 것은 가능하다.
2) const
중복선언 불가, 재할당 불가
const title = 'book';
console.log(title); // book
const title = 'movie';
console.log(title);
//Uncaught SyntaxError: Identifier 'title' has already been declared
title = 'music';
console.log(title);
//Uncaught TypeError: Assignment to constant variable
let와 const의 차이는 immutable(재할당)가능여부이다. 재할당은 가능한 let과 달리 const는 재할당 또한 불가하다.
그렇다면 const와 let중 어느것을 써야할까?
변수 선언시에는 기본적으로 const를 사용하고, 다른 값을 할당해야 할 상황이 생겼을 때 let를 사용하는게 좋다
2. 템플릿 문자열
ES2015 문법에 새로운 문자열이 생겻다. 이 문자열은 큰따옴표나 작은따옴표로 감싸는 기존 문자열과 달리 백틱(`)으로 감싼다.
특이한 점은 문자열 안에 변수를 넣을 수 있다는 점이다.
예제
var num1 = 1;
var num2 = 2;
var result = 3;
var string1 = num1 + ' 더하기' + '는 \'' + result + '\'';
console.log(string1);
const num3 = 1;
const num4 = 2;
const result2 = 3;
const string2 = `${num3} 더하기 ${num4}는 '${result2}'`;
console.log(string2);
3. 객체 리터럴
다음코드는 oldObject 객체에 동적으로 속성을 추가한다.
var sayNode = function() {
console.log('Node');
};
var es = 'ES';
var oldObject = {
sayJS: function(){
console.log('JS');
},
sayNode: sayNode,
};
oldObject[es + 6] = 'Fantastic';
oldObject.sayNode(); //Node
oldObject.sayJS(); //JS
console.log(oldObject.ES6); //Fantastic
이 코드를 다음과 같이 다시 쓸 수 있다.
const newObject = {
sayJS(){
console.log('JS');
},
sayNode,
[es + 6]: 'Fantastic',
};
newObject.sayNode(); //Node
newObject.sayJS(); //JS
console.log(newObject.ES6); //Fantastic
두 코드를 비교하면 sayJS같은 객체의 메서드에 함수를 연결할 때 콜론(:)과 function을 붙이지 않아도 된다
sayNode: sayNode처럼 속성명과 변수명이 동일한 경우에는 한번만 써도 되게 바뀌었다.
예를들어 {name: name, age: age} 같은 경우에도 {name, age}로 작성 할 수 있다.
객체의 속성명은 동적으로 생성 할 수 있다. newObject안에서 [es + 6]가 속성명으로 바로 사용되고 있다.
4. 화살표 함수 (arrow function)
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);
add1, add2, add3, add4는 같은 기능을 하는 함수이다.
화살표 함수에서는 function선언 대신 => 기호로 함수를 선언하고, 변수에 대입하면 나중에 재사용 할 수 있다.
그리고 내부에 return문 밖에 없는 경우, return문을 줄일 수 있다. add3와 add4처럼 return할 식을 바로 적으면 된다. (소괄호로 묶어서 사용할 수 도 있다)
function not1(x) {
return !x;
}
const not2 = x => !x;
not2처럼 매개변수가 한개면 매개변수를 소괄호로 묶지 않아도 된다.
기존 function과 다른점은 this바인딩 방식이다.
var relationship1 = {
name: 'zero',
friends: ['nero', 'hero', 'xero'],
logFriends: function () {
var that = this; //relationshiop1을 가리키는 this를 that에 저장
this.friends.forEach(function (friend){
console.log(that.name, friend);
});
},
};
relationship1.logFriends();
const relationship2 = {
name: 'zero',
friends: ['nero', 'hero', 'xero'],
logFriends(){
this.friends.forEach(friend => {
console.log(this.name, friend);
});
},
};
relationship2.logFriends();
relationship1.logFriends()안의 forEach문에는 furntion 선언문을 사용했다. 각자 다른 함수 스코프의 this를 가지므로 that이라는 변수를 사용해서 간접 접근한다.
relationship2.logFriends()안의 forEach문에서는 화살표 함수를 사용했다. 따라서 바깥 스코프인 logFriends()의 this를 그대로 사용할 수 있따. 상위 스코프의 this를 그대로 물려받은 것이다.
즉, 기본적으로 화살표 함수를 쓰되, this를 사용해야 하는 경우에는 화살표 함수와 함수 선언문 둘중 하나를 고르면 된다.
5. 구조 분해 할당
객체와 배열로부터 속성이나 요소를 쉽게 꺼내고 싶을 때 사용한다.
객체의 속성을 같은 이름의 변수에 대입하는 코드
var candyMachine = {
status: {
name: 'node',
count: 5,
},
getCandy: function(){
this.status.count--;
return this.status.count;
},
};
var getCandy = candyMachine.getCandy;
var count = candyMachine.status.count;
이코드를 다음과 같이 바꿀 수 있다
const candyMachine = {
status: {
name: 'node',
count: 5,
},
getCandy(){
this.status.count--;
return this.status.count;
},
};
const { getCandy, status: { count } } = candyMachine;
candyMachine 객체 안의 속성을 찾아서 변수와 매칭 한다. count처럼 여러 단계 안의 속성도 찾을 수 있다. getCandy와 count 변수가 초기화 된것이다.
배열에 대한 구조 분해 할당 문법
var array = ['nodejs', {}, 10, true];
var node = array[0];
var obj = array[1];
var bool = array[3];
해당 코드를 다음과 같이 바꿀 수 있다
const array = ['nodejs', {}, 10, true];
const [node, obj, , bool] = array;
6. 클래스
클래스 문법은 프로토타입 기반으로 동작한다.
프로토타입 상속 예제
var Human = function(type) {
this.type = type || 'human';
};
Human.isHuman = function(human) {
return human instanceof Human;
}
Human.prototype.breathe = function() {
alert('h-a-a-a-m');
};
var Zero = function(type, firstName, lastName){
Human.apply(this, arguments);
this.firstName = firstName;
this.lastName = lastName;
};
Zero.prototype = Object.create(Human.prototype);
Zero.prototype.constructor = Zero; //상속하는 부분
Zero.prototype.sayName = function() {
alert(this.firstName + ' ' + this.lastName);
};
var oldZero = new Zero('human', 'Zero', 'Cho');
Human.isHuman(oldZero); //true
Human 생성자 함수가 있고, 그 함수를 Zero 생성자 함수가 상속한다. Zero 생성자 함수를 보면 상속받기 위한 코드가 상당히 난해함을 볼 수 있다.
Human.apply와 Object.create 부분이 상속받는 부분이다.
위 코드를 클래스 기반으로 바꿔보자
class Human {
constructor(type = 'human') {
this.type = type;
}
static isHuman(human) {
return human instanceof Human;
}
breathe() {
alert('h-a-a-a-m');
}
}
class Zero extends Human {
constructor(type, firstName, lastName) {
super(type);
this.firstName = firstName;
this.lastName = lastName;
}
sayName() {
super.breathe();
alert(`${this.firstName} ${this.lastName}`);
}
}
const newZero = new Zero('human', 'Zero', 'Cho');
Human.isHuman(newZero);
전반적으로 class안으로 그룹화 된 것을 볼 수 있다. 생성자 함수는 ocnstructor 안으로 들어갔고, Human.isHuman같은 클래스 함수는 static 키워드로 전환되었다.
프로토타입함수들도 모두 class 블록 안에 포함돼서 어떤 함수가 어떤 클래스 소속인지 확인하기 쉽다. 상속도 간단해져서 extends 키워드로 쉽게 상속할 수 있다.
다만, 이렇게 클래스 문법으로 바뀌었더라도 자바스크립트는 프로토타입 기반으로 동작한다는걸 명심하자
7. 프로미스
https://learnjs.vlpt.us/async/01-promise.html
8. async/await
https://learnjs.vlpt.us/async/02-async-await.html
9. Map/Set
10. 널 병합/옵셔널 체이닝
참고 : ⌜node.js 교과서⌟ 책을 공부하며 요약・정리한 내용입니다.
'🎨 Web_Front end > JavaScript' 카테고리의 다른 글
s (0) | 2023.11.03 |
---|---|
변수와 자료형 그리고 연산자 (0) | 2023.10.31 |
이벤트 (0) | 2023.04.26 |
함수 (0) | 2023.04.26 |
객체 (내장객체, 브라우저 객체 모델, 문서 객체 모델) (0) | 2023.04.25 |