[ JS ] - 추가학습

200원짜리개발자·2024년 6월 13일
0

FrontEnd

목록 보기
24/29
post-thumbnail

제로베이스 자바스크립트 기초개념 추가학습 부분 정리
축약된 부분이 존재할 수 있습니다.

추가학습

사이사이 넣기 애매했던거 배우는 시간

구조 분해 할당

배열이나 객체의 구조에 맞게 바로 개별 변수에 값을 할당하는 방법으로,
필요한 값만 추출하여 변수에 할당할 수 있습니다.

배열 구조 분해 할당

const number = [1, 2, 3];
// const a = number[0];
// const b = number[1];
// const c = number[2];
const [a, b, c] = numbers;

console.log(a, b, c);

기본적으로 이렇게 동작이되고, 다양한 패턴들이 존재한다고 한다.
선언과 분리

const number = [1, 2, 3];
let a;
let b;
let c;
if (number.length) {
  [a, b, c] = numbers;
}
  
console.log(a, b, c);

선언과 분리를 하는 이유는 변수에는 scope라는 유효범위가 있는데 if문같은데 넣어서 선언을 해버린다면 밖에서는 사용할 수 없는 상황이 생길 수도 있기때문이다.
기본값

const number = [, , 3];
const [a = 0, b, c] = number;
  
console.log(a, b, c);

이런식으로 기본값을 지정해줄 수 있다.
반환 값 무시

const number = [1, 2, 3];
const [, , c] = number;
  
console.log(a, b, c);

이렇게 원하는 값만 빼먹을 수 있다.
나머지 할당

const number = [1, 2, 3];
const [a, ...rest] = number;
  
console.log(a, b, c);

객체 구조 분해 할당

const user = {
  name: "200won",
  age: 200,
  isValid: true,
};
// const name = user.name;
// const age = user.age;
// const isValid = user.isValid;
const { name, age, isValid } = user;
  
console.log(name, age, isValid);

객체 데이터는 순서가 없기때문에, 순서없이 적어도 사용가능하다.\
선언과 분리

const user = {
  name: "200won",
  age: 200,
  isValid: true,
};
let name;
let age;
let isValid;
if (user) {
  ({ name, age, isValid } = user);
}
  
console.log(name, age, isValid);

기본값

const user = {
  name: "200won",
  age: 200,
  isValid: true,
};
const { isValid = false } = user;
  
console.log(isValid);

변수명 변경

const user = {
  name: "200won",
  age: 200,
  isValid: true,
};
const { name: a, age: b, isValid: c } = user;
  
console.log(a, b, c);

이런식으로 객체를 받고 이름을 변경해서 변수를 생성할 수 있다.
기본값 + 변수명 변경

const user = {
  name: "200won",
  age: 200,
  isValid: true,
};
const { name: a, age: b, isValid: c = false } = user;
  
console.log(a, b, c);

나머지 할당

const user = {
  name: "200won",
  age: 200,
  isValid: true,
};
const { name, ...rest } = user;
  
console.log(name, rest);

배열과 동일하게 나머지 할당도 사용이 가능하다.

선택적 체이닝

?.

  • 대괄호 혹은 점 표기법의 대상이 null 혹은 undefined인 경우, 에러 대신 undefined를 반환합니다.
    우리가 변수를 활용하다보면 의도치 않게 null.abc라든가 이렇게 사용될 수 있을 때가 있다. 그럴 때 선택적 체이닝을 사용해서 에러없이 아래 코드를 실행시킬 수 있다!
console.log(null?.abc);
console.log(undefined?.abc);
  
const el = document.querySelector("h1");
console.log(el?.textContent);
  
// const numbers = [1, 2, 3];
const number = null;
// 대괄호에서도 쓸 수 있다 ㄷㄷ
console.log(numbers?.[0]);
  
const user = {
  name: "200원",
  age: 22,
};
// const user = null;
console.log(user?.name);

함수에도 user.func?.()처럼 사용할 수 있다.

모듈

자바스크립트 코드를 파일로 구분해서 데이터를 내보내거나 가지고 와서 사용할 수 있는 개념이다.

function add(a, b) {
  return a + b;
}
function sub(a, b) {
  return a - b;
}
function getUserBirthYear(user) {
  const year = new Date().getFullYear;
  return year - user.age;
}
const fruits = ["사과", "바나나", "체리"];
const addFruits = (fruit) => {
  fruits.push(fruit);
};
  
console.log(add(2, 7));
console.log(sub(2, 7));
  
const thw = {
  name: "200원",
  age: 200,
};
const hhm = {
  name: "황현민",
  age: 19,
};
console.log(getUserBirthYear(thw));
console.log(getUserBirthYear(hhm));
  
addFruits("오렌지");
addFruits("망고");
console.log(fruits);

위에 있는 함수들을 활용하고 있다.
그럼 이것을 모듈개념으로 정리해보자.

일단 계산하는 함수를 모아두는 calculator.js 파일을 만들어주자.

function add(a, b) {
  return a + b;
}
function sub(a, b) {
  return a - b;
}

그럼 이런식으로 작성하면 될까?
아니다 이제 import와 export라는 개념을 사용해줘야 한다.

// calculaotr.js
export function add(a, b) {
  return a + b;
}
export function sub(a, b) {
  return a - b;
}
// main.js

// 추가해주기
import { add, sub } from "./calculator.js";

그리고 또한 HTML에서 불러오는 js파일을 module와 시켜줘야 한다.

<script type="module" defer src="./main.js"></script>

이런식으로 모듈화를 시켜준다면, 작동이 잘 되는것을 알 수 있다.

그럼 따른 함수들도 모듈화를 시켜보자.

import { add, sub } from "./calculator.js";
import { getUserBirthYear } from "./user.js";
import { fruits, addFruits } from "./fruits.js";
  
console.log(add(2, 7));
console.log(sub(2, 7));
  
const thw = {
  name: "200원",
  age: 200,
};
const hhm = {
  name: "황현민",
  age: 19,
};
console.log(getUserBirthYear(thw));
console.log(getUserBirthYear(hhm));
  
addFruits("오렌지");
addFruits("망고");
console.log(fruits);

이런식으로 main.js에 있던 함수를 구분별로 모듈화를 시켰고, import로 main.js에 불러와서 사용할 수 있다.

이런식으로 하면 좀 더 간결하게 관리할 수 있어진다.
또한 기능들을 폴더에 넣어서 관리할 수도 있다.

import & export 사용 패턴

import & export를 하나라도 가지고 있으면 module이다.
import(가져오기)

  • JS 파일의 최상단에 위치해야 합니다.
import {} from "./module.js";

export(내보내기)

// 기본 내보내기(Default export)
// - 이름이 필요치 않습니다.
// - 모듈에서 1번만 사용할 수 있습니다.
// export default 데이터;
export default [1, 2, 3];
  
// 이름 내보내기(Named export)
// - 이름이 필수입니다.
// - 모듈에서 여러번 사용할 수 있습니다.
// export const 이름1 = 데이터1;
// export const 이름2 = 데이터2;
// export function 이름3() {}
// export const a = 1;
// export const b = 3;
  
const a = 1;
const b = 3;

// 모아서 내보내기 (객체 아님)
export { a as a1, b };
// 기본 내보내기는 이름을 import에서 지정함
// 이름 내보내기는 import에서 이름대로 가져오고 이름을 바꾸고 싶다면 as 사용
// 와일드카드(*)을 사용해서 다 가져올 수도 있음
import abc, { a as b } from "./module.js";
profile
고3, 프론트엔드

0개의 댓글