10. Next-Gen JavaScript
리액트 앱은 보통 가장 최신 버전의 자바스크립트와 차세대 기능을 이용, 깔끔하고 강력한 리액트 앱을 작성할 수 있게 해줌
또한 리액트 자체가 수많은 차세대 자바스크립트 기능을 이용함
JS는 아주 빠르게 진화하기 때문에 새로운 기능들은 다양한 모습으로 보여질 수 있고, 덕분에 개발자들은 더 강력한 것들을 만들 수 있음
JS를 쉽게 실행해볼 수 있는 Jsbin.com
JS Bin
Sample of the bin:
jsbin.com
11. 변수 let과 const
var: JS에서 변수를 생성함 let, const: ES6에서 변수를 생성하는 키워드
let - 새로운 var
- 변수 선언 시 사용
- 값을 수정할 수 있는 변수를 선언
const - 상수 선언
- 변하지 않는 값인 상수를 선언
- 상수: 절대 변하지 않는 수
12. 화살표 함수
자바스크립트 함수를 생성하는 또 다른 구문
일반적인 JS 함수
function myFnc() { ... } // or var myFnc() = function() { ... }
화살표 함수
const myFnc = () => { ... }
화살표 함수의 특징
- 키워드 function을 생략했기 때문에 일반적인 함수보다 짧음
- JS에서 갖고 있었던 this로 인한 문제들을 해결해줌
Jsbin 실습
function printMyName(name) {
console.log(name);
}
printMyName('Max');
const printMyName1 = (name) => {
console.log(name);
}
printMyName1('Max');
// 인수가 1개인 경우
const printMyName2 = name => {
console.log(name);
}
printMyName2('Max');
// 인수가 0개인 경우 - 빈 괄호쌍 무조건 입력
const printMyName3 = () => {
console.log('Max');
}
printMyName3();
// 인수가 2개인 경우
const printMyName4 = (name, age) => {
console.log(name, age);
}
printMyName4('Max', 28);
화살표 함수의 인수가 1개
() 생략 가능
화살표 함수의 인수가 0개
() 생략 불가능하고 빈 괄호 쌍 무조건 입력해줘야 함
화살표 함수의 인수가 2개
() 생략 불가능하고 괄호 안에 인수를 넣어 전달
return 키워드 생략
const multiple = (number) => {
return number * 2;
}
const multiply = num => num * 2;
console.log(multiply(2));
13. Exports와 Imports (Modules)
차세대 자바스크립트에서는 …
- 모듈 방식의 코드 작성 기능
- 여러 개의 파일로 코드 분할 가능모듈: JS 파일 안에 있는 것으로, 다른 파일에서 컨텐츠를 불러올 수 있고 JS 파일은 그 컨텐츠가 어디에서 온 것인지 알고 있음
- 코드를 여러 파일로 나누고 html 파일에 올바른 순서로 코드를 가져오기만 하면 됨!
Export Import 샘플
// person.js
const person = {
name: 'Max'
}
export default person
// utility.js
export const clean = () => {...}
export const baseData = 10;
// app.js
import person from './person.js'
import prs from './parson.js'
import { baseData as bD } from '/utility.js'
import { clean } from '/utility.js'
import { baseData, clean } from '/utility.js'
import * as bundled from '/utility.js'
bundled.baseData = 10;
default 키워드
default란: 파일에서 어떤 것을 가져오면 항상 default export가 내보낸 것을 기본값으로 가져온다는 의미
person.js에서, default 키워드를 사용하고 있는데, 이 경우에는 const person이 기본값이 된다. 즉, person.js에서 person을 import하면원하는 대로 객체의 이름을 지정할 수 있음
default 키워드를 지정하지 않았을 때의 경우
named export 사용: 불러오려는 것을 default로 지정하지 않았을 때 자바스크립트가 이를 정확히 알게 하기 위하여 중괄호 사이에 입력
💡 파일 안에서 정의된 *“정확한 이름”*을 export 키워드와 함께 써야 한다. 다만, as 키워드를 써서 별칭 할당 가능하다. 예를 들어, 여러 named export가 있는 경우 “import * as bundled” 구문 사용한다. (bundled.baseData, bundled.clean과 같이 사용)
utility.js에서, baseData를 가져올 때 {} 사이에 지정
14. 클래스(Classes)
클래스의 개념
클래스: 객체를 위한 핵심 청사진, 여기서는 “자바스크립트 객체 ”를 위한 청사진
class Person {
name = 'Max'; // Method
call = () => {...} // Property
}
클래스(≒생성자 함수)
new 키워드: 클래스의 인스턴스를 생성
const myPerson = new Person()
myPerson.call()
console.log(myPerson.name)
상속(≒오버라이딩)
다른 클래스에 있는 프로퍼티와 메소드를 상속하면 잠재적으로 새로운 프로퍼티와 메소드를 추가한다는 뜻
class Person extends Master
Class 샘플
class Human {
constructor() {
this.gender = 'male';
}
printGender() {
console.log(this.gender);
}
}
class Person extends Human {
constructor() {
// 상위 클래스의 생성자함수 실행
super();
this.name = 'Max';
// 변수 오버라이딩
this.gender = 'female';
}
printMyName() {
console.log(this.name);
}
}
const person = new Person();
person.printMyName();
person.printGender();
super 키워드
super: 상위 클래스의 생성자 함수를 실행
만약 하위 클래스에 super() 메소드를 추가하지 않는다면, 상위 클래스의 생성자 함수가 실행되지 않고 에러가 발생
15. 클래스, 속성 및 메서드
메소드, 프로퍼티란?
// ES6/Babel
class Human {
gender='male';
printGender=()=>{
console.log(this.gender);
}
}
class Person extends Human {
name='Max';
gender='female';
printMyName=()=>{
console.log(this.name);
}
}
const person = new Person();
person.printMyName();
person.printGender();
메소드(Method)
객체에 추가되는 함수
화살표 함수를 사용하면 this 키워드를 사용하지 않아도 됨
myMethod() {...} // ES6
myMethod = () => {...} // ES7
프로퍼티(Property)
클래스와 객체에 추가되는 변수
// ES6
constuctor() {
this.myProperty = 'value'
}
// ES7
myProperty = 'value'
16. 스프레드 및 나머지 연산자
점 3개 (…) 로 이루어진 연산자
어디에서 사용하냐에 따라 “스프레드” ******또는 “레스트”라고 함
스프레드(Spread)
배열의 원소나 객체의 프로퍼티를 나누는 데 사용 배열이나 객체를 펼쳐 놓음
const newArray = [...oldArray, 1, 2]
const newObject = {...oldObject, newProp: 5}
[ … oldArray, 1, 2]: oldArray 배열에 있는 모든 원소들을 새로운 배열에 추가하고, 거기에 1과 2를 더 추가하고 싶을 때 사용
[ … oldObject, newProp: 5}: ****객체는 중괄호와 키(newProp), 값을 써서 새 원소 생성 oldObject로 모든 프로퍼티와 값을 꺼내서 새 객체의 값으로 추가하고, 만약 oldObject가 newProp을 갖고 있었으면 5로 덮어쓰여질 것
나머지 연산자(Rest Operators)
함수의 인수 목록을 배열로 합치는 데 사용
function sortArgs(...args) {
return args.sort()
}
sortArgs( … args) 함수 sortArgs()는 매개변수를 무제한으로 받음 매개변수가 몇 개이든 우리는 …args로 씀 1개 이상의 매개변수를 갖게 되어도 모두 배열로 통합
스프레드와 레스트 실습
스프레드 - 배열
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4];
console.log(newNumbers); // [1, 2, 3, 4]
// 점 3개(...)를 안 쓰는 경우
const newNumbers2 = [numbers, 4];
console.log(newNumbers2); // [[1, 2, 3], 4]
이전 원소를 추가하지 않고도, 새 배열에 하나의 원소로 포함됨 (배열 복사)
스프레드 - 객체
const person = {
name: 'Max'
}
const newPerson = {
...person,
age: 28
}
console.log(newPerson); // name과 age 출력
이전 객체의 모든 프로퍼티 값을 복사하여, 새 자바스크립트 객체인 newPerson에 할당하고, 새로운 프로퍼티 age를 추가
레스트
const filter = (...args) => {
return args.filter(el => el === 1);
}
console.log(filter(1, 2, 3));
return을 이용하여 args를 반환하고, filter() 함수 호출 filter() 함수는 배열에서 전달되는 모든 원소들에 대해 함수를 실행 원소를 전달하고 화살표 함수를 사용해서 원소가 1과 같은지 아닌지 반환
17. 구조분해할당(Destructuring)
디스트럭쳐링
배열의 원소나 객체의 프로퍼티를 추출해서 변수에 저장
스프레드와의 차이점 스프레드: 모든 원소와 프로퍼티를 가져와서 새 배열이나 객체에 전달 디스트럭쳐링: 원소나 프로퍼티를 “하나만” 가져와서 변수에 저장
Array Destructuring
[a, b] = ['Hello', 'Max']
console.log(a) //Hello
console.log(b) //Max
변수 a와 b에 Hello와 Max를 각각 할당 ([a , b]라고 썼다고 해서 배열을 새로 생성하는 것은 아님)
Object Destructuring
{name} = {name: 'Max', age: 28}
console.log(name) //Max
console.log(age) //undefined
배열에 적힌 순서대로 프로퍼티가 디스트럭쳐링되기 때문에 객체에서 age는 추출되지 않으므로 undefined로 나옴
Jsbin 실습
const numbers = [1, 2, 3];
[num1, num2] = numbers;
console.log(num1, num2); //1과 2 출력
[num1, ,num3] = numbers;
console.log(num1, num3); //1과 3 출력
[]나 {}안에 있는 변수에 배열이나 객체가 순서대로 할당 건너뛰고 싶다면 공백 입력
18. 참조형 및 원시형 데이터 타입
첫번째 - 참조형과 기본형 자료 타입
const number = 1;
const num2 = number;
console.log(num2); //1
기본형
const number = 1; 과 같이 변수를 생성
number, string, boolean 등은 모두 기본형 자료 타입이고, 재할당하거나 변수를 다른 변수에 저장할 때마다 값을 복사함
참조형
const num2 = number;과 같이 변수를 설정 객체와 배열은 참조형 자료 타입임
참조형 자료 타입이라는 것은 변수명에 포인터를 저장한다는 것
Jsbin 실습
const person = {
name: 'Max'
};
const secondPerson = person;
console.log(secondPerson); //Max
person.name = 'Manu';
console.log(secondPerson); //Max가 아닌 Manu
secondPerson이 person의 값을 복사한 것은 아니고, 객체 person은 메모리에 저장되어있고 상수 person에는 메모리에 있는 주소를 가리키는 포인터를 저장함
‘=’: 포인터 복사(얕은 복사, Shallow Copy)
person을 secondPerson에 할당하면 포인터가 복사됨console.log(secondPerson); 시 Max가 아닌 Manu 출력됨
배열도 마찬가지로 적용되므로 주의할 것 다른 주소에 있는 같은 객체를 다르게 사용하도록 조작할 수 있음
‘Spread’: 변경할 수 없는 방법으로 복사(깊은 복사, Deep Copy)
const person = {
name: 'Max'
};
const secondPerson = {
...person
};
console.log(secondPerson); //Max
person.name = 'Manu';
console.log(secondPerson); //Max
포인터가 아닌 진짜 복사본을 생성했기 때문에 person.name = ‘Manu’;로 바꿔도 secondPerson은 Max가 출력됨
19. Refreshing Array Functions
Map() 함수
- 내장 배열 메소드 중 하나 (차세대 자바스크립트는 아님) 입력으로 함수(일반 or 화살표 함수) 받아 예전 값을 새 값으로 반환
- const numbers = [1, 2, 3]; const doubleNumArray = numbers.map((num) => {return num*2;}); console.log(numbers); //[1, 2, 3] console.log(doubleNumArray); //[2, 4, 6]
Filter() 함수
- 필터링 함수에서 True일 경우 해당 값 충족하는 새 배열 반환
- const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; const result = words.filter(word => word.length > 6); console.log(result); // expected output: Array ["exuberant", "destruction", "present"]
Reduce() 함수
- 배열의 각 요소를 리듀서 콜백을 실행하여 단일 값으로 줄임
- const array1 = [1, 2, 3, 4]; // 0 + 1 + 2 + 3 + 4 const initialValue = 0; const sumWithInitial = array1.reduce( (previousValue, currentValue) => previousValue + currentValue, initialValue ); console.log(sumWithInitial); // expected output: 10
20. 그 외 함수
Find() 함수
- 제공된 테스트 함수를 충족하는 배열의 첫 번째 요소 값을 반환
- const array1 = [5, 12, 8, 130, 44]; const found = array1.find(element => element > 10); console.log(found); // expected output: 12
FindIndex() 함수
- 제공된 테스트 함수를 충족하는 배열의 첫 번째 요소의 인덱스를 반환
- const array1 = [5, 12, 8, 130, 44]; const isLargeNumber = (element) => element > 13; console.log(array1.findIndex(isLargeNumber)); // expected output: 3
Concat() 함수
- 배열 + 배열 또는 배열 + 값인 새 배열을 반환
- const array1 = ['a', 'b', 'c']; const array2 = ['d', 'e', 'f']; const array3 = array1.concat(array2); console.log(array3); // expected output: Array ["a", "b", "c", "d", "e", "f"]
Slice() 함수
- 호출 배열의 섹션을 추출하여 새 배열을 반환
- const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(animals.slice(2)); // expected output: Array ["camel", "duck", "elephant"] console.log(animals.slice(2, 4)); // expected output: Array ["camel", "duck"] console.log(animals.slice(1, 5)); // expected output: Array ["bison", "camel", "duck", "elephant"] console.log(animals.slice(-2)); // expected output: Array ["duck", "elephant"] console.log(animals.slice(2, -1)); // expected output: Array ["camel", "duck"] console.log(animals.slice()); // expected output: Array ["ant", "bison", "camel", "duck", "elephant"]
Splice() 함수
- 배열에서 요소를 추가하거나 제거
- const months = ['Jan', 'March', 'April', 'June']; months.splice(1, 0, 'Feb'); // inserts at index 1 console.log(months); // expected output: Array ["Jan", "Feb", "March", "April", "June"] months.splice(4, 1, 'May'); // replaces 1 element at index 4 console.log(months); // expected output: Array ["Jan", "Feb", "March", "April", "May"]
Array 메서드를 사용하여 if문 간결화
Includes() 함수
- [배열].incldudes를 사용하여 다수의 조건 체크
if (name == "홍길동" || name == "박서방" || name= "김서방") { console.log(`${name}님 어서오세요!`); }
- // includes 메서드 사용 if (["홍길동", "박서방", "김서방"].includes(name)) { console.log(`${name}님 어서오세요!`); }
21. Array 함수 요약
**- forEach vs map vs reduce 차이**
-> foreach
- 배열 원소들을 반복하며 특정 액션 수행
- **값을 리턴하지 않아 단순 반복에 쓰임**
(내부에서 배열을 만드는 것도 되지만, 그럴 땐 보통 map 사용)
- 일반 for문보다 가독성이 좋고, 객체형을 다루기가 쉽다.
- **for문과 다르게 중간에 끊을 방법이 없음**
map
- 배열 원소들을 반복하며 값을 변경해 리턴. 즉 새로운 배열 생성
- map을 실행하는 배열과 결과로 나오는 배열이 다른 객체라는 것입니다.
기존 배열을 수정하지 않고 새로운 배열을 만들어냅니다
- 보통 배열 전체 값을 변경할 때 사용
- 정리하자면, map은 배열을 1대1로 짝짓되 기존 객체를 수정하지 않는 메서드입니다.
filter
- filter의 가장 큰 특징은 boolean형태의 return값을 갖는다.
- 배열 원소들을 반복하며 조건에 true면 원소를 남기고, flase면 삭제. 새로운 배열 생성
- return값이 true일경우, 그 요소를 반환하고 false일경우, 반환하지 않는다.
기본값은 false이다.
- 배열 값 중 의미 없는 값 버릴 때 사용. 말 그대로 필터링
+ 빈 배열 요소를 반환하지 않음
대용량 배열 처리시 메모리 overflow 가능성이 있음
reduce
- 배열의 각 요소를 순회하며 callback함수의 실행 값을 누적하여 하나의 결과값을 반환
- 첫번째 인자인 accumulator 는 return값을 누적하는데, 계속해서 전달받아서 사용할 수도 있다.
- 배열 원소들을 반복하며 값을 조합해 하나의 결과 값 리턴 ex.sum, avg
- map과 filter과 같은 함수형 메서드를 모두 reduce로 모두 구현할 수 있습니다.
sort, every, some, find, findIndex, includes도 다 reduce로 구현 가능
반복되는 모든 것에는 reduce를 쓸 수 있음
-> 덧셈 등의 사칙 연산, 최대값과 최소값 구하기
some
- 배열 원소 중 하나라도 조건을 만족하면 true, 아니면 false 반환
- 배열에서 특정 값 검사 or 특정상황에서 멈추는 반복문 만들 때 사용
every
- 배열 원소 모두가 조건을 만족하면 true, 하나라도 아니면 false 반환
- 배열 모든 원소 검사. break도 가능하긴 함
22. 차세대 JavaScript - 요약 1
let & const
var: 재선언 & 재할당 가능 let: 재할당만 가능 const: 둘 다 불가
let은 block-scoped 변수
let x = 1;
if (x === 1) {
let x = 2;
console.log(x);
// expected output: 2
}
console.log(x);
// expected output: 1
const는 block-scoped 상수
const number = 42;
try {
number = 99;
} catch (err) {
console.log(err);
// expected output: TypeError: invalid assignment to const `number'
// Note - error messages will vary depending on browser
}
console.log(number);
// expected output: 42
ES6 Arrow Functions
- Arrow Function은 JavaScript 환경에서 함수를 생성하는 또 다른 방법 this 키워드의 범위를 유지하는 데 유리
- function callMe(name) { console.log(name); } //1 const callMe = function(name) { console.log(name); } //2 const callMe = (name) => { console.log(name); } //3 //1, 2, 3은 같다
중요한 점
- arguments가 없는 경우, 빈 괄호를 사용해야 함
- const callMe = () => { console.log('Max!'); }
- 정확히 하나의 argument가 있는 경우, 괄호를 생략 가능
- const callMe = name => { console.log(name); }
- value를 return할 때, 다음과 같은 숏컷 사용
- const returnMe = name => name //1 const returnMe = name => { return name; } //2 //1, 2는 같다
제한 사항
- 자체 바인딩이 없음 [this](<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this>), 또는 , Method로는 사용할 수 없습니다.
- 키워드에 액세스할 수 없음
- [call](<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call>), [apply](<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply>)그리고 스코프에 의존하는 방법에는 적합하지 않음
- 생성자로 사용할 수 없음
- 본문 내에서 [yield](<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield>)를 사용할 수 없음
23. 차세대 JavaScript - 요약 2
Exports & Imports
사용하는 이유
React 프로젝트에서 (그리고 실제로 모든 최신 JavaScript에서), 모듈이라 불리는 여러 자바스크립트 파일들에 코드를 분할함 이렇게 하면 각 모듈의 목적을 명확하게 하고 관리가 용이함
다른 파일의 기능에 계속 액세스하려면 export (available하게 하기 위해) 및 import 엑세스를 확보하기 위해) statements가 필요함
두 가지 유형의 Export: default(unnamed)와 named
default ⇒ export default ...; named ⇒ export const someData = ...;
두 가지 유형의 Import
default ⇒ import someName from './path/to/file.js'; named ⇒ import { someData } from './path/to/file.js'; ****named 모두 import ⇒ import * as upToYou from './path/to/file.js'; upToYou.someData로 upToYou에 액세스할 수 있음
Classes
- Classes는 constructor 함수와 prototypes를 대체하는 기능 자바스크립트 객체에 blueprints를 정의할 수 있음class의 property(⇒ name)이 정의됨 해당 구문은 property를 정의하는 구식구문임
- class Person { constructor () { this.name = 'Max'; } } //1 class Person { name = 'Max'; } //2 const person = new Person(); console.log(person.name); // prints 'Max' //1과 2는 같음 class Person { name = 'Max'; printMyName () { console.log(this.name); // this is required to refer to the class! } } //3 class Person { name = 'Max'; printMyName = () => { console.log(this.name); } // 이때 `this`키워드가 reference를 변경하지 않는 이점 }//4 const person = new Person(); person.printMyName(); //3과 4는 같음
- Class 사용 시 inheritance 사용
- class Human { species = 'human'; } class Person extends Human { name = 'Max'; printMyName = () => { console.log(this.name); } } const person = new Person(); person.printMyName(); console.log(person.species); // prints 'human'
Spread & Rest Operator: ...
- 배열에서 요소들을 가져오거나 (⇒배열을 요소들의 리스트로 분해) 객체에서 속성을 가져옴
- const oldArray = [1, 2, 3]; const newArray = [...oldArray, 4, 5]; // This now is [1, 2, 3, 4, 5]; const oldObject = { name: 'Max' }; const newObject = { ...oldObject, age: 28 }; console.log(newObject); /* 출력될 것 { name: 'Max', age: 28 } */
Destructing
- 배열이나 객체의 값에 쉽게 접근 가능, 변수에 할당 가능
- const array = [1, 2, 3]; const [a, b] = array; console.log(a); // prints 1 console.log(b); // prints 2 console.log(array); // prints [1, 2, 3] - 배열일 때 const myObj = { name: 'Max', age: 28 } const {name} = myObj; console.log(name); // prints 'Max' console.log(age); // prints undefined console.log(myObj); // prints {name: 'Max', age: 28} - 객체
- 인자를 가진 함수를 작업할 때 매우 유용
- const printName = (personObj) => { console.log(personObj.name); } //일반적인 방법 const printName = ({name}) => { console.log(name); } //Destructing 사용 printName({name: 'Max', age: 28}); // prints 'Max'
'React.js > React.js 완벽 가이드 with TS, Redux, Next.js' 카테고리의 다른 글
섹션 5: 렌더링 리스트 및 조건부 Content (0) | 2023.07.03 |
---|---|
섹션 4: 리액트 State 및 이벤트 다루기 (0) | 2023.04.19 |
섹션 3: 리액트 기초 및 실습 컴포넌트 (0) | 2023.04.17 |
섹션 1: 시작하기 - What is react? And Why would we use it? What is SPA? (0) | 2023.04.17 |