본문 바로가기
  • 기록
React/(Udemy)React-The Complete Guide

[React] 기본 자바스크립트 문법

by juserh 2022. 4. 7.

1. let, const

자바스크립트에서 var을 쓸 수 있지만 ES6의 let과 const를 쓰는 것을 권장한다.

  • let: 가변 변수
  • const: 상수(할당 후 수정X)

노드에서는 주로 const를 쓴다!

var
let
const

위 실행결과를 보면 const의 경우 처음 변수에 할당한 값은 콘솔에 출력되지만, 값을 변경하고 이를 출력하고자 하면 에러가 뜬다. const는 새 값을 할당하면 안된다.

 


2. 화살표 함수(Arrow Functions)

const myFunc = () =>{
	...
}

위와 같은 방식으로 사용한다. 함수 이름 다음으로 등호가 등장하고 그 다음 괄호 안에 인수가 있다면 함수 인수를 작성한다. 그리고 화살표 다음에 함수 내용을 담는다. 화살표 함수가 유용한 이유는 기존 자바스크립트 함수 정의할 때보다 길이가 짧고, this 키워드를 사용할 수 있다는 점 때문이다.

기본 함수 정의
화살표함수
화살표함수-인수, 반환
화살표함수-괄호 생략

 


3. Exports, Imports (modules)

  • default exports: 기본 내보내기
  • named exports: 이름으로 내보내기
//person.js 
const person={
	name: 'juserh'
}

export default person

 

//utility.js
export const clean = () => {..}
export const baseData = 10;

 

//app.js
import person from './person.js'
import prs from './person.js'

import {baseData} from './utility.js'
import {clean} from './utility.js'

위 코드를 살펴보면 person.js 안의 person 개체는 default export이기 때문에 person.js 파일에서 import할 경우 무조건 person 개체가 기본(default)으로 내보내진다. 따라서 app.js에서는 person.js 파일에서 import해 가져온 것의 이름을 바꿀 수 있다. app.js 코드를 살펴보면 person.js 파일로부터 import한 것의 이름을 person, prs로 이름 붙인 것을 볼 수 있고 이들은 모두 person 객체를 의미한다.

반면 utility.js 파일은 clean함수와 baseData변수를 그냥 export 했는데 이는 named export로, app.js는 이들을 import 할 때 그들의 이름을 통해야한다. 따라서 중괄호{}안의 그 이름으로 해당하는 것을 불러온다(그러니 이름을 정확히 입력해야 할 것임).

그런데....named export에도 별칭(alias)를 붙일 수 있다고 한다.

import {baseData as bd} from './utility.js'

위와 같이 as 키워드 다음에 원하는 별칭을 정할 수 있다.

또, 한 파일에서 여러 개를 import하고 싶다면

import * as bundled from './utility.js'

위오 같이 * as를 이용해 가져올 수 있다. bundled.clean, bundled.baseData로 내보내기 가능하다.

 


4. 클래스(Class):

blueprint for javascript object, very comparable to constructor functions where inheritance is comparable to prototypes.

클래스 구성요소

  • property: 속성(변수)
  • method: 함수

클래스는 new 키워드로 인스턴스화된다. constructor function을 사용해서 생성자 정의할 수 있다.

extends키워드로 상속(inheritance) 가능하다(prototype?).

클래스 상속

다른 클래스를 상속할 경우 constructor function에 super consturctor를 불러주기 위한 메서드인 super() 메서드를 추가해주어야 한다.

 


5. 클래스, 속성, 메소드(Class, Property, Method)

바로 앞의 코드를 이렇게 바꿀 수 있다.

(constructor function 생략 가능, property 초기화 시 'this.' 생략 가능)

 


6. 스프레드(Spread), 나머지 연산자

... 연산자: 용도에 따라 나뉨

  • spread operator(스프레드 연산자): used to split up array elements or object properties, 배열을 편리하게 복사하거나 예전 객체의 속성들을 가져와 추가하고자 할 때 등에 사용됨
  • rest operator(나머지 연산자): used to merge a list of function arguments into an array, 매개변수 무한정으로 받고 그것이 배열로 합쳐짐

spread operator-배열

...을 붙이지 않으면 위와 같은 결과가 나온다(배열 안의 배열).

spread operator-객체

spread operator를 객체에 적용한 코드이다. person의 속성을 그대로 가져오고 추가로 작성한 age 속성까지 출력되는 것을 확인할 수 있다.

rest operator

rest operator(근데 찾아보니 보통은 rest parametor라고 하는 듯) ... 는 인수 개수를 제한 없이 받을 수 있고 이를 배열로 합친다. 위 코드를 살펴보면 모든 인수들을 배열로 받은 args에 배열의 fliter함수를 적용해 1과 같은 값을 필터링하여 출력하여 위와 같은 결과가 나온다.

 

 


7. 구조분해할당(Destructuring)

easily extract array elements or object properties and store them in variables.

spread operator와 비슷한 것 같지만, 다르다. spread operator는 모든 요소, 속성을 새 배열 혹은 객체에 분배한다. 그러나 destructuring은 한 요소, 속성만을 배열이나 객체를 위한 변수로 저장한다.

  • array destructuring
  • object destructuring

array destructuring

//object destructuring
{name}={name: 'juserh', age:28};
console.log(name); //juserh
console.log(age); //undefined

object destructuring은 jsbin에서 실행되지 않아서 코드로 남깁니다...!

 

 


8. 참조형 및 원시형 데이터 타입(Reference, Primitive types)

  • primitive type: numbers, string, boolean 등 -> whenever i reassign or store a valiable in another valiable, it will copy the value.
  • reference type: object, array -> not copy. store pointer.

primitive type

위 경우에는 number의 값을 num1에 복사돼서 두 변수는 같은 값을 갖게 된다.

reference type

이 경우에는 person이 secondPerson에 복사되지 않는다. person 객체는 메모리에 저장되고, secondPerson은 메모리에 포인터를 저장한다. 그리고 person을 secondPerson에 할당하면 person의 포인터가 복사되는 것이다.

이를 확인하기위해 코드를 수정해보자.

reference type

콘솔에 secondPerson을 출력하기 전에 person의 name속성을 바꿔주었다. 그리고 secondPerson의 출력 결과도 바뀐 것을 볼 수 있다. 앞서 언급했듯이, 객체는 객체 그 자체를 복사해오는 것이 아니라 포인터를 복사해오는 것이기 때문에 실제로는 같은 객체를 지정하고 있어 이런 결과가 발생한 것이다. 배열도 마찬가지.

이처럼 예상치 못한 결과가 발생할 수 있기 때문에 리액트에서는 이 부분을 주의해야한다.

 

그렇다면, 이런 일이 발생하지 않도록 객체 그 자체를 복사하는 방법은 무엇일까? 바로 spread operator을 사용하는 것이다.

spread operator로 객체 복사

spread operator를 이용하면 person 객체의 속성과 그 값들을 모두 추출해 secondPerson 객체에 추가할 수 있다. 이전과 마찬가지로 person객체의 속성을 바꾸고 secondPerson을 출력하면....그 결과 아까와는 달리 본래 값으로 나오는 것을 볼 수 있다. 즉, secondPerson이 person의 포인터를 저장한 것이 아니라 person 객체를 실제로 '복사'해서 가져왔다는 것이다.

 

객체와 배열은 reference type이기 때문에 이들을 재할당하면, 값을 복사하는 것이 아니라 포인터를 복사하는 것임을 명심하자!

 


9. 배열 함수(Array functions)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

 

Array - JavaScript | MDN

The Array object, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name, and has members for performing common array operations.

developer.mozilla.org

  • map()
  • find()
  • findIndex()
  • filter()
  • reduce()
  • concat()
  • slice()
  • splice()

등이 있다.

map 예

 


https://developer.mozilla.org/en-US/docs/Web/JavaScript

 

JavaScript | MDN

JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js, Apache

developer.mozilla.org

여기서 추가적으로 참고합시다!