📌71. 제네레이터 함수
function* startGame() {
const answer = yield 'Do you love JavaScript?';
if (answer !== 'Yes') {
return "Oh wow... Guess we're done here";
}
return 'JavaScript loves you back ❤️';
}
const game = startGame();
console.log(game.next().value); // Do you love JavaScript?
console.log(game.next("Yes").value); // JavaScript loves you back ❤️
- yield 의 값인 answer는 아직 정해지지 않은 상태로 함수가 멈추게 된다
- next() 안에 인수를 전달하면, yield가 인수로 교체되어 answer의 값이 할당된다 (answer = "Yes")
72. String.raw 정적 메서드
console.log(String.raw`Hello\nworld`); // Hello\nworld
String.raw
- 템플릿 리터럴의 태그 함수로, 문자열 내부의 \n 등의 이스케이프 문자열을 무시하고 모두 그대로 출력한다
- 아래 예시처럼 파일 경로를 표시할 때 유용하다
const path = `C:\Documents\Projects\table.html`;
console.log(path); // C:DocumentsProjects able.html
console.log(String.raw`C:\Documents\Projects\table.html`); // C:\Documents\Projects\table.html
74. push() 메서드
function addToList(item, list) {
return list.push(item);
}
const result = addToList('apple', ['banana']);
console.log(result); // 2
- push 메서드는 새로운 배열의 길이를 반환한다
76. global scope
const { firstName: myName } = { firstName: 'Lydia' };
console.log(firstName); // ReferenceError
ReferenceError가 발생하는 조건
- JS에서는 현재 스코프에서 변수를 찾을 수 없는 경우, 스코프 체인을 따라 최상위 스코프(global scope)까지 올라간다
- 전역 객체에서도 변수를 못 찾으면, ReferenceError를 반환한다
예) name 변수의 경우
- 브라우저에서는 window.name 이 deprecated 이므로 빈 문자열 ""를 반환
- Node에서는 전역 객체에 name이 없으므로 ReferenceError 발생
88. default parameter
function sum(num1, num2 = num1) {
console.log(num1 + num2);
}
sum(10); // 20
- default parameter의 값을 다른 parameter로 설정할 수 있다
- 단, 먼저 정의된 parameter이어야 한다
📌89. import * as name
// module.js
export default () => 'Hello world';
export const name = 'Lydia';
// index.js
import * as data from './module';
console.log(data); // { default: function default(), name: "Lydia" }
- import * as name 으로 다른 모듈을 가져올 경우, name 이라는 이름의 객체에 export 되는 값들이 프로퍼티로 저장된다
- default export의 경우, default 프로퍼티에 저장된다
- 나머지 개별 export의 경우, 그 이름으로 된 프로퍼티에 저장된다
92. prototype
function giveLydiaPizza() {
return 'Here is pizza!';
}
const giveLydiaChocolate = () =>
"Here's chocolate... now go hit the gym already.";
console.log(giveLydiaPizza.prototype); // { constructor: ... }
console.log(giveLydiaChocolate.prototype); // undefined
- 일반 함수: prototype 프로퍼티 가짐
- 화살표 함수: prototype 프로퍼티 갖지 않음
📌94. rest parameter
function getItems(fruitList, ...args, favoriteFruit) {
return [...fruitList, ...args, favoriteFruit]
}
getItems(["banana", "apple"], "pear", "orange")
- rest parameter는 반드시 마지막 매개변수 자리에 있어야 한다
- 남아있는 모든 매개변수들을 배열로 받기 때문이다
96. class 재할당
class Person {
constructor() {
this.name = 'Lydia';
}
}
Person = class AnotherPerson {
constructor() {
this.name = 'Sarah';
}
};
const member = new Person();
console.log(member.name); // Sarah
- 클래스는 재할당이 가능하다
97. Object.keys()
const info = {
[Symbol('a')]: 'b',
};
console.log(info); // {Symbol('a'): 'b'}
console.log(Object.keys(info)); // []
- Symbol은 enumerable 하지 않다
- Object.keys() 로 배열을 만들 때, 객체의 enumerable한 프로퍼티의 키값만 가져오기 때문에, Symbol은 보이지 않는다
- Object.getOwnPropertySymbols() 메서드를 사용하면 객체의 Symbol 프로퍼티만 배열로 가져올 수 있다
참고