[Node.js] 알아둬야 할 자바스크립트
화살표 함수
화살표 함수의 기본 구문
// Without parameters
const func = () => {
// Function body
};
// With parameters
const add = (a, b) => {
return a + b;
};
// If the function body has only one expression, you can omit the curly braces and the return keyword
const multiply = (a, b) => a * b;
this 바인딩
화살표 함수의 중요한 차이점 중 하나는 자체 this 컨텍스트가 없다는 것입니다. 대신, 바깥쪽 범위에서 this를 상속합니다. 이 동작은 특정 상황, 특히 콜백을 처리하고 .bind()의 필요성을 피할 때 유리할 수 있습니다.
function Counter() {
this.count = 0;
// Traditional function expression
setInterval(function () {
this.count++; // 'this' refers to the global object or undefined (in strict mode)
console.log(this.count);
}, 1000);
// Arrow function
setInterval(() => {
this.count++; // 'this' refers to the Counter object
console.log(this.count);
}, 1000);
}
const counter = new Counter();
즉, 화살표함수를 사용하면 상위 스코프의 this를 그대로 물려받습니다.
또한 기본적으로 화살표 함수를 쓰되, this를 사용해야 하는 경우에는 화살표 함수와 함수선언문 둘 중 하나를 고르면 됩니다.
암시적 반환:
함수 본문이 단일 표현식으로 구성된 경우 중괄호 {}와 return 키워드를 생략할 수 있습니다. 표현식의 결과가 자동으로 반환됩니다.
const add = (a, b) => a + b; // implicit return
단일 매개변수 함수에 대한 간결한 구문:
함수에 매개변수가 하나만 있는 경우 매개변수 목록 주위의 괄호를 생략할 수 있습니다.
// Traditional function expression
const square1 = function (x) {
return x * x;
};
// Arrow function with one parameter
const square2 = x => x * x;
어휘 범위 지정:
화살표 함수에는 자체 인수 개체가 없습니다. 대신, 바깥쪽 범위에서 상속합니다. 또한 자체 super가 없기 때문에 클래스 생성자 내에서 메서드를 정의하는 것과 같은 특정 사용 사례에 적합하지 않습니다.
function Example() {
this.name = 'Example';
// Traditional function expression
this.printName1 = function () {
console.log(this.name);
};
// Arrow function (lexically scoped 'this')
this.printName2 = () => {
console.log(this.name);
};
}
const example = new Example();
example.printName1(); // 'Example'
example.printName2(); // 'Example'
화살표 기능을 사용해야 하는 경우:
- this의 어휘 범위를 유지하려면 화살표 기능을 사용하세요.
- 짧고 간결한 함수, 특히 함수를 인수로 전달해야 하는 경우(예: 고차 함수)에 사용하세요.
화살표 기능을 사용하지 말아야 할 경우:
- 'super'에 액세스해야 하는 객체 리터럴 또는 클래스 생성자 내부의 메서드에 화살표 함수를 사용하지 마세요.
- '인수' 개체가 필요할 때는 화살표 기능을 사용하지 마세요.
요약하면 화살표 함수는 JavaScript에서 함수를 정의하기 위한 간결하고 편리한 구문을 제공합니다. 여기에는 어휘적 'this' 컨텍스트, 단일 표현식에 대한 암시적 반환 및 간결한 구문이 있어 특정 시나리오에서 특히 유용합니다. 그러나 다양한 상황에서 효과적으로 사용하려면 특히 'this' 바인딩 및 범위 지정 측면에서 차이점을 인식하는 것이 중요합니다.
구조 분해 할당
구조 분해 할당은 ECMAScript 6(ES6)에 도입된 강력한 기능으로, 배열에서 값을 추출하거나 객체에서 속성을 추출하여 간결하고 표현적인 방식으로 변수에 할당할 수 있습니다. 복잡한 데이터 구조 작업에 보다 편리한 구문을 제공합니다. 구조 분해 할당은 배열, 객체 및 기타 반복 가능한 구조에서 작동합니다.
Array Destructuring:
기본 배열 분해:
// Traditional approach
const numbers = [1, 2, 3];
const first = numbers[0];
const second = numbers[1];
// With array destructuring
const [first, second] = numbers;
console.log(first); // 1
console.log(second); // 2
요소 건너뛰기:
const numbers = [1, 2, 3, 4, 5];
// Skipping the first and third elements
const [, second, , fourth] = numbers;
console.log(second); // 2
console.log(fourth); // 4
나머지 매개변수:
const numbers = [1, 2, 3, 4, 5];
// Destructuring with rest parameter
const [first, ...rest] = numbers;
console.log(first); // 1
console.log(rest); // [2, 3, 4, 5]
Object Destructuring:
기본 객체 구조화:
// Traditional approach
const person = { firstName: 'John', lastName: 'Doe' };
const firstName = person.firstName;
const lastName = person.lastName;
// With object destructuring
const { firstName, lastName } = person;
console.log(firstName); // John
console.log(lastName); // Doe
변수 이름 바꾸기:
const person = { firstName: 'John', lastName: 'Doe' };
// Renaming variables during destructuring
const { firstName: first, lastName: last } = person;
console.log(first); // John
console.log(last); // Doe
기본값:
const person = { firstName: 'John' };
// Setting default values during destructuring
const { firstName, lastName = 'Doe' } = person;
console.log(firstName); // John
console.log(lastName); // Doe
중첩 객체 해체:
const person = {
name: { first: 'John', last: 'Doe' },
age: 30,
};
// Nested object destructuring
const {
name: { first, last },
age,
} = person;
console.log(first); // John
console.log(last); // Doe
console.log(age); // 30
함수의 매개변수 구조화:
구조 분해를 함수 매개변수와 함께 사용하여 값을 직접 추출할 수도 있습니다.
// Traditional approach
function printName(person) {
const firstName = person.firstName;
const lastName = person.lastName;
console.log(`${firstName} ${lastName}`);
}
// With parameter destructuring
function printName({ firstName, lastName }) {
console.log(`${firstName} ${lastName}`);
}
const person = { firstName: 'John', lastName: 'Doe' };
printName(person); // John Doe
사용 사례:
- 변수 교체:
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1
함수에서 여러 값 반환:
function getCoordinates() {
return [x, y];
}
const [x, y] = getCoordinates();
React에서 속성 추출:
const MyComponent = ({ prop1, prop2 }) => {
// ...
};
// Instead of using props.prop1 and props.prop2
API 및 JSON 데이터 작업:
const fetchData = async () => {
const response = await fetch('https://api.example.com/data');
const { data, status } = await response.json();
};
구조 분해 할당은 더 깔끔하고 읽기 쉬운 구문을 제공하여 코드를 더 간결하고 표현력 있게 만듭니다. 이는 최신 JavaScript 개발에 널리 사용되며 이를 활용하는 방법을 이해하면 코드의 명확성과 유지 관리 가능성을 크게 향상시킬 수 있습니다.
Map, Set
// Creating an empty Map
const myMap = new Map();
// Creating a Map with initial key-value pairs
const fruits = new Map([
['apple', 3],
['banana', 5],
['orange', 2],
]);
기본 작업:
// Adding entries to the Map
fruits.set('grape', 4);
// Getting the value associated with a key
console.log(fruits.get('banana')); // 5
// Checking if a key exists
console.log(fruits.has('orange')); // true
// Deleting an entry
fruits.delete('apple');
// Iterating over entries
for (const [key, value] of fruits) {
console.log(`${key}: ${value}`);
}
크기 및 클리어:
// Getting the number of entries in the Map
console.log(fruits.size);
// Clearing all entries from the Map
fruits.clear();
사용 사례:
- 유연한 키 유형: Map을 사용하면 개체를 포함한 광범위한 키 유형을 사용할 수 있으므로 다용도로 사용할 수 있습니다.
- 순서 보존: 키의 순서가 중요한 경우 Map을 사용하면 순서가 유지됩니다.
- 항목 반복: 'for...of' 루프를 사용하면 키-값 쌍을 쉽게 반복할 수 있습니다.
set
'set'는 각 값이 고유해야 하는 고유한 값의 모음입니다. 중복 항목을 허용하지 않으며 요소의 순서는 삽입 순서에 따라 결정됩니다.
set 만들기:
// Creating an empty Set
const mySet = new Set();
// Creating a Set with initial values
const colors = new Set(['red', 'green', 'blue']);
기본 작업:
// Adding values to the Set
colors.add('yellow');
// Checking if a value exists
console.log(colors.has('green')); // true
// Deleting a value
colors.delete('red');
// Iterating over values
for (const color of colors) {
console.log(color);
}
size 및 클리어:
// Getting the number of values in the Set
console.log(colors.size);
// Clearing all values from the Set
colors.clear();
사용 사례:
- 고유성: 고유한 값을 저장해야 할 경우 'Set'을 사용하여 자동으로 중복 항목을 제거합니다.
- 순서 보존: Map과 유사하게 Set은 삽입 순서에 따라 요소의 순서를 유지합니다.
- 멤버십 확인: '세트'에 값이 존재하는지 확인하는 것은 빠르고 효율적인 작업입니다.
Map vs Set:
- 키-값 대 고유 값: 'Map'은 키-값 쌍용으로 설계된 반면, 'Set'은 고유한 값용으로 설계되었습니다.
- 순서 보존: Map과 Set 모두 삽입 순서에 따라 요소의 순서를 유지합니다.
- 사용 사례: 키와 값 사이의 연관을 처리할 때 Map을 사용하세요. 고유한 값 모음으로 작업할 때는 'Set'을 사용하세요.
요약하자면 Map과 Set은 JavaScript의 데이터 구조에 강력한 추가 기능입니다. 이는 애플리케이션의 특정 요구 사항에 따라 다양한 시나리오에서 유연성, 효율성 및 사용 편의성을 제공합니다. 각각의 차이점과 사용 사례를 이해하면 특정 요구 사항에 적합한 데이터 구조를 선택하는 데 도움이 됩니다.