JS 기초

  1. JavaScript란?
    1. 변수
    2. 함수
      1. 콜백 함수
    3. 객체(Object)
    4. 클래스(Class)
      1. 접근제어자
      2. getter & setter
      3. 예제: 직원 월급 고지
      4. 비동기
        1. Promise
          1. Promise: 병렬 처리
        2. async
      5. Hooks
    5. Promise와 async & await
  2. NodeJS란?

JavaScript란?

image description

  • Ecma International의 프로토타입 기반의 프로그래밍 언어로, 스크립트 언어.

동작

  • 자바스크립트 엔진이 런타임시 인터프리터가 코드를 한줄 씩 번역하여 실행시켜준다.

JavaScript 더 알아보기

변수

let

  • 재할당 가능 변수
    let a = 10;
    console.log(a) //10
    a = 3
    console.log(a) //3
    

const

  • 재할당 불가능한 변수
    const a = 10;
    console.log(a) //10
    a = 3 //ERROR
    console.log(a) //ERROR
    

var (⚠️최대한 사용하지 않기)

함수

IIFE (Immediately Invoked Function Exporessions)
바로 실행하는 함수

(function run(){
    console.log("Hello")
})();

콜백 함수

  • 함수를 가르키고 있는 함수의 참조값을 전달한다. ```js const add = (a, b) => a + b; const multiple = (a, b) => a * b;

const addOrMul = (x, y, action) => { return action === add ? add(x, y) : multiple(x, y); };

console.log(addOrMul(2, 3, multiple));


### 생성자 함수
```js
function createIdCard(name, age) {
  this.name = name;
  this.age = age;
}

firstId = new createIdCard('Holmes', 31);
secondId = new createIdCard('Harry', 22);

console.log(firstId);
console.log(secondId);

객체(Object)

key, value

속성 삭제 delete object.key

동적으로 속성에 접근 💡 매개변수 key의 형태를 모르기에 대괄호를 사용하는 것이 포인트!!

const idCard = {
  name: 'Holmes',
  age: 30,
};
const showValue = (object, key) => {
  return object[key];
};
console.log(showValue(idCard, 'name')); //Holmes

클래스(Class)

  • 객체를 생성하는 템플릿. ```js class createIdCard { constructor(name, age) { this.name = name; this.age = age; } }

firstId = new createIdCard(‘Holmes’, 31); secondId = new createIdCard(‘Harry’, 22);

console.log(firstId); console.log(secondId);

💡 클래스를 통하여 만들어진 객체는 인스터스라고 한다.

### static
- 한번만 사용되고 인스턴스에는 포함되지 않는 함수.
```js
class createIdCard {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  // 클래스 레벨의 메서드
  static makeIdCard() {
    return new createIdCard('John', 47);
  }
}

firstId = new createIdCard('Holmes', 31);
secondId = new createIdCard('Harry', 22);

const thirdId = createIdCard.makeIdCard();

console.log(firstId);
console.log(secondId);
console.log(thirdId);

접근제어자

  • 클래스 외부에서 접근하지 못하도록 한다.
class createIdCard {
  #name;
  #age;
  constructor(name, age) {
    this.#name = name;
    this.#age = age;
  }
}

firstId = new createIdCard('Holmes', 31); //접근 불가 ERROR
secondId = new createIdCard('Harry', 22); //접근 불가 ERROR

getter & setter

class createIdCard {
  name;
  age;
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  //접근 시 호출
  get intro() {
    return `안녕하세요 저는 ${this.name}이고 나이는 ${this.age}살 입니다.`;
  }
  //할당 시 호출
  set intro(value) {
    return console.log(`저는 ${value}입니다.`);
  }
}

firstId = new createIdCard('Holmes', 31);

console.log(firstId.intro);

firstId.name = 'John';
console.log(firstId.intro);

firstId.intro = 'Dobby';
console.log(firstId.intro);

예제: 직원 월급 고지

class Employee {
  constructor(name, part, workPerMonth, salaryPerHour) {
    this.name = name;
    this.part = part;
    this.workPerMonth = workPerMonth;
    this.salaryPerHours = salaryPerHour;
  }
  calculateSalary() {
    const salary = this.workPerMonth * this.salaryPerHours;
    return `${this.part} 팀의 ${this.name}님의 월급은 ${salary}`;
  }
}
class FullEmployee extends Employee {
  static SALARY_PER_HOUR = 15000;
  constructor(name, part, workPerMonth) {
    super(name, part, workPerMonth, FullEmployee.SALARY_PER_HOUR);
  }
}

class PartEmployee extends Employee {
  static SALARY_PER_HOUR = 8000;
  constructor(name, part, workPerMonth) {
    super(name, part, workPerMonth, PartEmployee.SALARY_PER_HOUR);
  }
}

const harry = new FullEmployee('nick', 'frontend', 225);
const dobby = new PartEmployee('john', 'backend', 250);
console.log(harry.calculateSalary());
console.log(dobby.calculateSalary());

forEach for in for of spread


비동기

Promise

Promise: 병렬 처리
function getBanana() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('바나나');
    }, 1000);
  });
}
function getApple() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('사과');
    }, 3000);
  });
}
function getOrange() {
  return Promise.reject(new Error('Orange is Gone'));
}

getBanana()
  .then((banana) =>
    getApple().then((apple) => {
      return [banana, apple];
    })
  )
  .then((a) => console.log('basic', a)); //1 + 3 = 4초 뒤 출력

Promise.all([getBanana(), getApple()]).then((a) => console.log('all', a)); //3초 뒤 출력

async

프로토타입

Hooks

useState useEffect useReducer useImmer

  • 객체를 직관적으로 관리할 수 있다. 설치: npm install immer use-immer

context API

useCallback memo useLocation useMatch useContext


Promise와 async & await


  const createUser = () => {
    return new Promise((resolve) => resolve(prompt('이름 입력...')));
  };

  const delay = () => {
    return new Promise((resolve) => setTimeout(() => resolve(console.log('Delay Done')), 3000));
  };
  async function checkUser() {
    console.log('Start');
    await delay();
    const username = await createUser();
    await delay();
    if (username === 'Harry') return `Hello ${username}`;
    return `GET OUT ${username}`;
  }

  checkUser().then((res) => console.log(res));

NodeJS란?

Image

  • 설명

Node.JS 더 알아보기