Front/React

리액트 ES6 문법 정리

oodada 2023. 10. 27. 01:05
반응형

리액트 ES6 문법 정리

1. 변수

변수는 let, const 키워드를 사용하여 선언한다.

let value = 1
console.log(value) // 1

value = 2
console.log(value) // 2

const a = 1
a = 2 // 에러 발생

2. 템플릿 문자열 (Template String)

템플릿 문자열은 문자열 안에 변수와 연산식을 넣을 수 있습니다.

const string1 = '안녕하세요.';
const string2 = '김겨울입니다.';
const greeting = ${string1} + ' ' + ${string2};
// 병합 연산자를 사용한 문자열 연결

const cat = {
  kind: '러시안블루',
  age: '1살',
};
const catInfo = `저는 ${cat.kind}이고, ${cat.age}입니다.`;
// 백틱(`)을 사용한 문자열 표현을 리터럴 문자열이라고 합니다.

const multiLine = '문자열을 \n여러 줄에 걸쳐 작성하면 \n줄바꿈이 됩니다.';
// 줄바꿈을 할 때는 이스케이프 시퀀스(\n)를 사용합니다.

const number1 = 1;
const number2 = 2;
const result = `${number1} * ${number2} = ${number1 * number2}`;

const boolean = true;
const booleanResult = '블리언 값은' + (boolean ? '참' : '거짓') + '입니다.';

문제

  • 템플릿 문자열을 사용하여 다음 문장을 출력해보세요.
    대괄호 안에 있는 내용은 변수로 대체합니다.
제 이름은 [odada]이고 나이는 [100]살입니다.
전화번호는 [010-1234-5678]이고 주소는 [서울시]입니다.

3. 삼항(Ternary) 연산자

조건 ? 참 : 거짓

console.log(true ? 1 : 2) // 1
console.log(false ? 1 : 2) // 2

if문 표현

const p = 1

if (p < 3) {
    console.log('참!!') // 참!!
} else {
    console.log('거짓') // 거짓
}

삼항 연산자 표현

  • 위의 코드를 삼항 연산자로 표현하면 다음과 같다.
console.log(p < 3 ? '참!!' : '거짓') // 참!!

ex

function isAnimal(text) {
    return text === '고양이' ? '고양이' : '고양이 아님'
}

console.log(isAnimal('고양이')) // 고양이
console.log(isAnimal('개')) // 고양이 아님

4. 전개(Spread) 연산자

...a, ...b

배열의 전개

const q = [1, 2, 3]
const r = [4, 5, 6]

const s = q.concat(r) // concat 메서드 사용
console.log(s) // [ 1, 2, 3, 4, 5, 6 ]

const t = [...q, ...r] // 전개 연산자
console.log(t) // [ 1, 2, 3, 4, 5, 6 ]

객체의 전개

const dog = {
    name: '멍멍이',
}
const dogInfo = {
    ...dog,
    age: 2,
}
console.log(dogInfo) // { name: '멍멍이', age: 2 }

함수의 인자에서의 전개

function sum(a, b, c) {
    console.log(a + b + c)
}

sum(1, 2, 3) // 6

// 배열 데이터를 인자로 전달하려면?
const num = [1, 2, 3]
sum(num[0], num[1], num[2]) // 6 (기존 방식)

// 전개 연산자를 사용하면?
sum(...num) // 6

5. 비구조화 할당 (구조 분해)

비구조화 할당은 객체와 배열로부터 속성이나 요소를 쉽게 꺼낼 수 있습니다.

객체 비구조화 할당

const object = { a: 1, b: 2 }

const { a, b } = object
console.log(a) // 1
console.log(b) // 2

// 비구조화 할당을 하는 과정에서 이름을 바꿀 수도 있습니다.
const object = { a: 1, b: 2 }

const { a: c, b: d } = object // a -> c, b -> d
console.log(c) // 1
console.log(d) // 2

// 비구조화 할당을 하는 과정에서 기본값을 설정할 수도 있습니다.
const object = { a: 1 }

const { a, b = 2 } = object
console.log(a) // 1
console.log(b) // 2

// 비구조화 할당을 하는 과정에서 함수의 인수에서도 사용할 수 있습니다.
const object = { a: 1 }

function print({ a, b = 2 }) {
    console.log(a)
    console.log(b)
}

print(object) // 1, 2

배열 비구조화 할당

const array = [1, 2]

const [one, two] = array
console.log(one) // 1
console.log(two) // 2

// 비구조화 할당을 하는 과정에서 기본값을 설정할 수도 있습니다.
const array = [1]

const [one, two = 2] = array
console.log(one) // 1

// 비구조화 할당을 하는 과정에서 함수의 인수에서도 사용할 수 있습니다.
const array = [1, 2]

function print([one, two]) {
    console.log(one)
    console.log(two)
}

print(array) // 1, 2

6. 함수의 인수

함수의 인수에서도 비구조화 할당을 사용할 수 있습니다.

function add({ a, b }) {
    // 비구조화 할당
    return a + b
}

const result = add({ a: 1, b: 2 }) // 인수에 객체를 넣어서 호출

console.log(result) // 3

7. 클래스

클래스는 ES6에서 새롭게 도입된 문법입니다. 기존에 존재하던 프로토타입을 베이스로 하고 있습니다.

// 클래스를 선언할 때는 class 키워드를 사용하고 클래스 이름은 파스칼 케이스로 작성합니다.
class Animal {
    // constructor 메서드를 작성하여 생성자를 설정합니다.
    constructor(type) {
        this.type = type // 클래스의 초기 상태를 설정합니다.
    }
    // 클래스 내부에서 함수를 선언할 때는 function 키워드를 생략한 메서드를 작성합니다.
    type() {
        console.log(this.type) // 클래스 내부에서 멤버 변수를 선언할 때는 const, let, var 키워드를 사용하지 않습니다.
    }
}

const dog = new Animal('개')
const cat = new Animal('고양이')

dog.type() // 개
cat.type() // 고양이

클래스 상속

  • extends 키워드를 사용하여 상속을 구현합니다.
    커피를 클래스로 정의함으로써, 각 커피 객체의 속성과 기능을 캡슐화하고 재사용할 수 있게 됩니다. 이를 통해 코드의 구조화, 조직화가 이루어지고, 새로운 커피 종류를 추가하거나 변경하기 쉬워집니다.
class Front {
    constructor(name, price) {
        this.name = name
        this.price = price
    }
    calling() {
        return `${this.name}는 ${this.price}원 입니다.`
    }
}

// Front 클래스를 상속받는 Special 클래스를 생성한다.
class Special extends Front {
    // Special 클래스의 프로토타입에 specialCoffee() 메소드를 생성한다.
    specialCoffee() {
        return `specialCoffee : ${this.name} ${this.price}`
    }
}

// Special 생성자 함수를 통해 객체를 생성한다.
const americano = new Special('악마 음료 슈렉 프라푸치노', 6000)
const latte = new Special('고디바 프라푸치노', 7000)

console.log(americano.calling()) // 아메리카노는 3000원 입니다.
console.log(latte.calling()) // 라떼는 4000원 입니다.
console.log(americano.specialCoffee()) // Special Class에서 상속받은 메소드 : 아메리카노 3000
console.log(latte.specialCoffee()) // Special Class에서 상속받은 메소드 : 라떼 4000

8. 화살표 함수

화살표 함수는 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: x, y: y })

function not1(x) {
    return !x
}

const not2 = (x) => !x

화살표 함수와 this

  • 화살표 함수는 this 바인딩이 없습니다. 따라서 화살표 함수 내부에서 this를 사용하면, 그 this는 상위 스코프의 this를 가리킵니다.
const cat = {
    name: '나비',
    sound: '야옹',
    say: function () {
        console.log(this.sound) // 야옹
    },
}

cat.say()

const dog = {
    name: '멍멍이',
    sound: '멍멍',
}

dog.say = cat.say
dog.say() // 멍멍
  • 위의 코드에서 dog.say()를 호출하면 멍멍이가 나와야 할 것 같지만, 야옹이 나옵니다. 이는 say 함수가 호출될 때 this가 상위 스코프인 전역 객체를 가리키기 때문입니다. 이를 해결하기 위해서는 bind 함수를 사용해야 합니다.
const dog = {
    name: '멍멍이',
    sound: '멍멍',
}

dog.say = cat.say.bind(dog)
dog.say() // 멍멍
  • bind 함수를 사용하여 this를 고정시켜주었습니다. 하지만 이 방법은 코드가 길어지고 복잡해질 수 있습니다. 이를 해결하기 위해서는 화살표 함수를 사용하면 됩니다.
const cat = {
    name: '나비',
    sound: '야옹',
    say: function () {
        console.log(this.sound) // 야옹
    },
}

cat.say()

const dog = {
    name: '멍멍이',
    sound: '멍멍',
}

dog.say = cat.say.bind(dog)
dog.say() // 멍멍

const catSay = cat.say
catSay() // 야옹

const catSay2 = cat.say.bind(cat)
catSay2() // 야옹

const catSay3 = cat.say.bind(dog)
catSay3() // 멍멍
  • catSay 함수는 cat.say를 가리키고 있습니다. catSay2 함수는 cat.say를 가리키고 있지만, bind 함수를 사용하여 this를 cat으로 고정시켜주었습니다. catSay3 함수는 cat.say를 가리키고 있지만, bind 함수를 사용하여 this를 dog로 고정시켜주었습니다.

9. 객체 리터럴

객체 리터럴은 중괄호({})를 사용하여 객체를 선언하는 것을 의미합니다.

const dog = {
    name: '멍멍이',
    age: 2,
    sound: '멍멍',
    say() {
        // say: function() {}의 축약형
        console.log(this.sound)
    },
}

dog.say() // 멍멍

ES6의 객체 리터럴

  • ES6에서는 객체 리터럴을 좀 더 간략하게 작성할 수 있습니다.
const name = '멍멍이'
const age = 2
const sound = '멍멍'

const dog = {
    name: name,
    age: age,
    sound: sound,
    say() {
        console.log(this.sound)
    },
}

dog.say() // 멍멍
  • 위의 코드를 ES6의 객체 리터럴로 작성하면 다음과 같습니다.
const name = '멍멍이'
const age = 2
const sound = '멍멍'

const dog = {
    name,
    age,
    sound,
    say() {
        console.log(this.sound)
    },
}

dog.say() // 멍멍

10. 배열 내장 함수

배열 내장 함수는 배열을 다룰 때 유용한 함수입니다.

forEach

  • forEach 함수는 배열 안에 들어있는 각 원소에 대하여 함수를 한 번씩 실행합니다.
const array = [1, 2, 3, 4]

array.forEach((num) => {
    console.log(num)
})

// 1
// 2
// 3
// 4

map

  • map 함수는 배열 안에 들어있는 각 원소를 변환할 때 사용합니다.
const array = [1, 2, 3, 4]

const squared = array.map((n) => n * n)
console.log(squared) // [ 1, 4, 9, 16 ]
// 1 * 1 = 1
// 2 * 2 = 4
// 3 * 3 = 9
// 4 * 4 = 16

indexOf

  • indexOf 함수는 원소의 인덱스를 찾아줍니다.
  • 원소가 없다면 -1을 반환합니다.
const array = ['사과', '바나나', '포도', '사과']

console.log(array.indexOf('사과')) // 0
console.log(array.indexOf('바나나')) // 1
console.log(array.indexOf('포도')) // 2
console.log(array.indexOf('수박')) // -1

findIndex

  • findIndex 함수는 indexOf 함수와 비슷합니다. 원소의 인덱스를 찾아줍니다.
  • 조건에 맞는 원소가 없다면 -1을 반환하는 대신, undefined를 반환합니다.
const array = ['사과', '바나나', '포도', '사과']

console.log(array.findIndex((fruit) => fruit === '사과')) // 0
console.log(array.findIndex((fruit) => fruit === '바나나')) // 1
console.log(array.findIndex((fruit) => fruit === '포도')) // 2
console.log(array.findIndex((fruit) => fruit === '수박')) // -1

find

  • find 함수는 findIndex 함수와 비슷합니다. 원소의 값을 찾아줍니다.
  • 조건에 맞는 원소가 없다면 -1을 반환하는 대신, undefined를 반환합니다.
const array = ['사과', '바나나', '포도', '사과']

console.log(array.find((fruit) => fruit === '사과')) // 사과
console.log(array.find((fruit) => fruit === '바나나')) // 바나나
console.log(array.find((fruit) => fruit === '포도')) // 포도
console.log(array.find((fruit) => fruit === '수박')) // undefined

filter

  • filter 함수는 배열에서 특정 조건을 만족하는 원소들만 따로 추출하여 새로운 배열을 만듭니다.
const array = [1, 2, 3, 4, 5, 6, 7, 8]

const even = array.filter((n) => n % 2 === 0) // 짝수만 추출
console.log(even) // [ 2, 4, 6, 8 ]

splice

  • splice 함수는 배열에서 특정 항목을 제거할 때 사용합니다.
const array = [1, 2, 3, 4, 5]

const index = array.indexOf(2) // 2의 인덱스를 찾아서
array.splice(index, 1) // 2의 인덱스부터 1개를 지웁니다.

console.log(array) // [ 1, 3, 4, 5 ]

slice

  • slice 함수는 배열을 잘라낼 때 사용합니다.
const array = [1, 2, 3, 4, 5]

const sliced = array.slice(0, 2) // 인덱스 0부터 2까지 잘라낸다.
console.log(sliced) // [ 1, 2 ]
console.log(array) // [ 1, 2, 3, 4, 5 ]

shift

  • shift 함수는 배열에서 첫 번째 원소를 추출할 때 사용합니다.
const array = [1, 2, 3, 4, 5]

const shifted = array.shift() // 첫 번째 원소를 추출합니다.
console.log(shifted) // 1
console.log(array) // [ 2, 3, 4, 5 ]

pop

  • pop 함수는 배열에서 마지막 원소를 추출할 때 사용합니다.
const array = [1, 2, 3, 4, 5]

const popped = array.pop() // 마지막 원소를 추출합니다.
console.log(popped) // 5
console.log(array) // [ 1, 2, 3, 4 ]

push

  • push 함수는 배열의 마지막에 새로운 원소를 추가할 때 사용합니다.
const array = [1, 2, 3, 4, 5]

array.push(6) // 마지막에 6을 추가합니다.
console.log(array) // [ 1, 2, 3, 4, 5, 6 ]

unshift

  • unshift 함수는 배열의 첫 번째에 새로운 원소를 추가할 때 사용합니다.
const array = [1, 2, 3, 4, 5]

array.unshift(0) // 첫 번째에 0을 추가합니다.
console.log(array) // [ 0, 1, 2, 3, 4, 5 ]

concat

  • concat 함수는 여러 개의 배열을 하나의 배열로 합쳐줍니다.
const array1 = [1, 2, 3]
const array2 = [4, 5, 6]

const concated = array1.concat(array2)
console.log(concated) // [ 1, 2, 3, 4, 5, 6 ]

join

  • join 함수는 배열 안의 값들을 문자열 형태로 합쳐줍니다.
const array = [1, 2, 3, 4, 5]

console.log(array.join()) // 1,2,3,4,5
console.log(array.join(' ')) // 1 2 3 4 5
console.log(array.join(', ')) // 1, 2, 3, 4, 5

reduce

  • reduce 함수는 배열의 각 원소에 대하여 주어진 함수를 실행하고, 하나의 결과값을 반환합니다.
const array = [1, 2, 3, 4, 5]

const result = array.reduce((accumulator, current) => {
    // accumulator는 누적값, current는 현재값
    console.log({ accumulator, current }) // 누적값과 현재값을 출력
    return accumulator + current // 누적값 + 현재값
}, 0) // 초기값 0

console.log(result)

11. 비동기 처리

비동기 처리는 특정 코드의 연산이 끝날 때까지 코드의 실행을 멈추지 않고 다음 코드를 먼저 실행하는 자바스크립트의 특성을 의미합니다.

setTimeout

  • setTimeout 함수는 특정 시간이 지난 후에 함수를 실행합니다.
function work() {
    setTimeout(() => {
        const start = Date.now() // 현재 시각을 저장하고
        for (let i = 0; i < 1000000000; i++) {} // 0 ~ 999999999까지 반복문을 실행한 후
        const end = Date.now() // 현재 시각을 저장합니다.
        console.log(end - start + 'ms') // 걸린 시간을 밀리초로 출력합니다.
    }, 0) // 0ms 이후에 콜백 함수를 실행합니다.
}

console.log('작업 시작!') // 작업 시작!이 먼저 출력됩니다.
work() // work 함수를 호출합니다.
console.log('다음 작업') // 다음 작업이 먼저 출력됩니다.
// '작업 시작'과 '다음 작업'이 먼저 출력되고
// 위에 for문을 1000000000번 반복하는 반복문을 실행하는 동안에는 다른 작업을 할 수 없기 때문에 브라우저가 멈춰있는 것처럼 보입니다.
// 1000000000번 반복하는 반복문이 실행되고 걸린 시간을 출력합니다.
// 이것이 비동기 처리로 작업이 끝날 때까지 기다리지 않고 다음 작업을 수행하는 것을 의미합니다.

콜백 함수

  • 콜백 함수는 함수의 인자로 전달되는 함수를 의미합니다.
function work(callback) {
    setTimeout(() => {
        const start = Date.now()
        for (let i = 0; i < 1000000000; i++) {}
        const end = Date.now()
        console.log(end - start + 'ms')
        callback(end - start)
    }, 0)
}

console.log('작업 시작!')
work((ms) => {
    // 콜백 함수를 전달합니다.
    console.log('작업이 끝났어요!')
    console.log(ms + 'ms 걸렸다고 해요.')
})
console.log('다음 작업')

Promise를 사용하여 API를 요청하기

  • Promise는 콜백 함수의 단점을 보완하기 위해 ES6에서 도입된 기능입니다.
// src/UsersList.js
import React, { useState, useEffect } from 'react'
import { Box, List, ListItem, ListIcon, Heading } from '@chakra-ui/react'

function UsersList() {
    // useState() : 컴포넌트의 상태를 관리하는 함수
    // const [상태변수, 상태변수를 변경할 수 있는 함수] = useState(초기값)
    // [] : 배열 비구조화 할당
    const [users, setUsers] = useState([])

    // useEffect(콜백함수, [의존성배열]) : 컴포넌트가 처음 렌더링될 때만 실행
    useEffect(() => {
        // fetch() : 네트워크 요청을 보내는 함수
        fetch('https://jsonplaceholder.typicode.com/users')
            // .then() : 비동기 처리가 성공했을 때 실행할 코드를 작성하는 함수
            // response.json() : JSON 형식의 데이터를 자바스크립트 객체로 변환하는 함수
            // 예를 들어, API로부터 {"name": "Alice", "age": 30} 형태의 JSON 데이터를 받았다면,
            // response.json()을 호출하여 이 데이터가 자바스크립트 객체 {name: "Alice", age: 30}으로 변환됩니다.
            // 이렇게 변환된 객체는 자바스크립트 코드 내에서 쉽게 접근하고 조작할 수 있게 됩니다.
            .then((response) => response.json())
            // data : JSON 형식의 데이터
            // setUsers(data) : users 상태변수를 변경하여 users 상태변수에 data를 저장
            .then((data) => setUsers(data))
            // .catch() : 비동기 처리가 실패했을 때 실행할 코드를 작성하는 함수
            .catch((error) => console.error(error))
    }, [])

    return (
        <Box p={5} shadow="md" borderWidth="1px">
            <Heading mb={4}>Users</Heading>
            <List spacing={3}>
                {users.map((user) => (
                    <ListItem key={user.id}>{user.name}</ListItem>
                ))}
            </List>
        </Box>
    )
}

export default UsersList
반응형
티스토리 친구하기