1. let & const
- 변수를 선언할 때 사용
- let (is like new var) ⇒ 값을 수정할 수 있는 변수를 선언할때 (variable values)
- const ⇒ 한번 지정하면 절대 변하지 않는 값(상수)를 선언할 때 사용(constant values)
- let myName = 'Max'; myName = 'Mike'; console.log(myName) // "Mike" const myName = 'Max'; myName = 'Mike'; console.log(myName) // TypeError : Assignment to constant variable.
2. Arrow Functions
- 키워드 function을 생략했기 때문에 일반적인 함수보다 짧다.
- JS에서 갖고 있었던 this 키워드로 인해 생겼던 많은 문제들을 해결해주는 장점이 있다.
// 일반적인 함수 형태
function myFnc() {
...
}
// Arrow Functions
const myFnc = () => {
...
// 이 안에서 this 키워드를 사용하면 항상 정의한 객체를 나타내고,
// 실행 중에 갑자기 바뀌지 않는다.
}
// 1. 오직 1개의 인수(argument)를 받는다면, 소괄호 생략가능
// 단, 전달 인수가 없다면 (), n개 이상의 인수를 받는다면 ( n, n+1 )
const printMyName = name => {
console.log(name);
}
printMyName('Max');
// 2. 화살표 함수의 유일한 문장이 'return'일 때 'return'과
// 중괄호({})를 생략할 수 있다.
const multiply = (number) => {
return number+2;
}
// 생략 후
const multiply = (number) => number * 2;
const multiply = number => number * 2; // 인수가 1개 일때 () 생략 가능
3. Exports & Imports (Modules)
- export default ⇒ 키워드는 파일에서 어떤 것을 가져오면 default export가 내보낸 것을 기본값으로 가져온다는 것을 의미한다.
- named export ⇒ 어떤 각각의 다른 상수를 불러오는데 그 파일에서 특정한 어떤 것을 정확하게 가르키기 위해 사용하며 { } 안에 상수명이 들어간다.
// person.js
const person = {
name: 'Max'
}
export default person
// utility.js
export const clean = () => {...}
export const baseData = 10;
//app.js
// ------------------ default export ------------------
import person from './person.js'
import prs from './person.js' // 이름을 바꿔도 default로 표시한 것을 참조한다.
// ------------------ named export ------------------
import { clean } from './utility.js'
import { baseData } from './utility.js'
import { clean, baseData } from './utility.js'
import { smth as Smth } from './utility.js'
import * as bundle from './utility.js' // 이 경우 ex) bundle.clean 처럼 사용가능
4. Classes (객체 지향 문법)
- 객체를 위한 like 청사진 ⇒ JS에서는 자바스크립트 객체
class Person {
name = 'Max' // Property : 클래스에 정의한 변수
call = () => {...} // Method : 클래스에 정의한 함수
}
const myPerson = new Person() // new 키워드로 클래스의 인스턴스를 생성
myPerson.call()
console.log(myPerson.name)
- 클래스는 상속(extends) 하여 사용할 수 있다. ⇒ 다른 클래스에 있는 Property와 Method를 상속하면 잠재적으로 새로운 Property와 Method를 추가한다는 뜻
class Human {
constructor() {
this.gender = 'male';
}
printGender() {
console.log(this.gender);
}
}
class Person extends Human { // Person 클래스에 Human 클래스를 상속받아 확장
constructor() {
super(); // 확장 사용을 위해서는 super 생성자를 먼저 호출해야함
this.name = 'Max';
this.gender = 'female';
}
printMyName() {
console.log(this.name);
}
}
const person = new Person();
person.printMyName();
person.printGender();
5. Classes, Properties & Methods
- Properties are like “variables attached to classes / objects” ⇒ 클래스와 객체에 추가되는 변수 같은 것
- Methods are like “functions attached to classes / objects” ⇒ 클래스와 객체에 추가되는 함수 같은 것
- ES6 vs ES7 - this 키워드를 사용 X , 따라서 ES7에서 해당 구문을 사용
- Property - ES7에서는 클래스에 바로 프로퍼티를 할당할 수 있다.
// ES6
constructor() {
this.myProperty = 'value'
}
// ES7
myProperty = 'value' // 생성자 함수를 호출하지 않아도 된다.
- Method
// ES6
myMethod () {...}
// ES7
myMethod = () => {...}
- ES7 문법을 이용한 예제
class Human {
gender = 'male';
printGender = () => {
console.log(this.gender); // this.gender 을 찍어도 "female" 잘 출력됨
}
}
class Person extends Human {
name = 'Max';
gender = 'female';
printMyName = () => {
console.log(this.name);
}
}
const person = new Person();
person.printMyName();
person.printGender();
6. Spread & Rest Operators (스프레드 & 나머지 연산자 ) - …
- Spread - Used to split up array elements OR object properties
⇒ 배열의 원소나 객체의 프로퍼티를 나누는데 사용
// oldArray 배열에 모든 원소를 새 배열에 추가하고 1, 2를 추가
const newArray = [ ...oldArray, 1, 2 ]
// oldObject의 모든 프로퍼티와 값을 꺼내서 새 객체의 키값으로 추가
const newObject = { ...oldObject, newProp: 5 }
- Rest - Used to merge a list of function arguments into an array
⇒ 함수의 인수 목록을 배열로 합치는데 사용
// sortArgs는 매개변수를 무제한으로 받고 매개변수가 몇 개이든 ...args라고 표기
// 매개변수 목록에 배열 메소드를 적용하거나 원하는 편한 방법으로 매개변수를 저장
function sortArgs{...args} {
return args.sort()
}
// ex)
const filter = (...args) => {
return args.filter(el => el === 1);
}
console.log(filter(1, 2, 3)); // 결과값은 [1]
7. Destructuring (구조분해할당)
- Easily extract array elements or object properties and store them in variables ⇒ 배열의 원소나 객체의 프로퍼티를 추출해서 변수에 저장할 수 있도록 해준다.
// Array Destructuring
[a, b] = ['Hello', 'Max']
console.log(a) // Hello
console.log(b) // Max
// Object Destructuring
{ name } = { name: 'Max', age: 28 }
console.log(name) // Max
console.l0g(age) // undefined
[Javascript][ES6] 객체 구조 분해 할당 (Object Destructuring) / 전개 구문 (Spread Operator) / Rest parameter
객체 구조 분해 할당 (Object Destructuring) 구조 분해 할당(Destructuring)은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식이다. 우리는 Object Destructuring을 알
snupi.tistory.com
8. 참조형 및 원시형 데이터 타입 (Not Next-Gen)
- 원시형(기본형 자료) 타입은 재할당, 변수를 다른 변수에 저장할 때마다 값을 복사한다.
const number = 1;
const num2 = number;
console.log(num2); // 결과값 : 1
- 참조형(객체와 배열) 타입은 복사가 아니라 메모리에 있는 주소를 가리키는 포인터 저장
// person의 프로퍼티 값을 바꿨는데 secondPerson도 값이 바뀐다.
// 포인터를 복사했고 person이 가리키는 메모리에 있는 동일한 객체를 가리키기 때문
const person = {
name: 'Max'
};
const secondPerson = person;
console.log(secondPerson); // 결과값 : { name: "Max" }
person.name = 'Manu';
console.log(secondPerson); // 결과값 : { name: "Manu" }
// Spread 연산자를 썼을 때
// person 이 재할당 되더라도 secondPerson 의 프로퍼티는 기존 복사값을 유지한다.
const secondPerson = {
...person // => Spread 연산자를 통해 포인터가 아닌 프로퍼티 복사
};
9. JS Array Functions (Not Next-Gen)
React 는 불변의 방식으로 배열 작업에 의존하기 떄문에 🔽이와 같은 함수를 많이 사용
- map(), find(), findIndex(), filter(), reduce(), concat(), slice(), splice()
- map()
Array.prototype.map() - JavaScript | MDN
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
developer.mozilla.org
-
- find()
Array.prototype.find() - JavaScript | MDN
The find() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
developer.mozilla.org
-
- findIndex()
Array.prototype.findIndex() - JavaScript | MDN
The findIndex() method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
developer.mozilla.org
-
- filter()
Array.prototype.filter() - JavaScript | MDN
The filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
developer.mozilla.org
-
- reduce()
Array.prototype.reduce() - JavaScript | MDN
The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the a
developer.mozilla.org
-
- concat()
Array.prototype.concat() - JavaScript | MDN
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
developer.mozilla.org
-
- slice()
Array.prototype.slice() - JavaScript | MDN
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
developer.mozilla.org
-
- splice()
Array.prototype.splice() - JavaScript | MDN
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice().
developer.mozilla.org
'Language > JavaScript' 카테고리의 다른 글
Promise & Async Await (0) | 2022.11.10 |
---|---|
[JavaScript] 비동기를 구현하는 방법 (Event loop & Callback) (0) | 2022.11.09 |
비동기에 대해서 (0) | 2022.11.08 |
Iterator & Generator (0) | 2022.10.29 |
[JavaScript] 유사 배열 객체(Array-like objects) (0) | 2022.03.23 |