tech.junha.kr

노트/JavaScript

ES 6 or higher

작성 수정

Arrow Function

  • 4가지 함수는 모두 동일한 함수다.
function func(a) {
  return a
}

const func = (a) => {
  return a
}

const func = a => {
  return a
}

const func = a => a;
  • return을 생략할 수 있지만, 객체 리턴시 주의.
// ❌ 아무값도 리턴하지 않음
const func = (name) => {id:1, name:name};
const func = (name) => {
  id:1, name:name
};


// ✅
const func = (name) => {
    return {id:1, name:name}
}

// ✅
const func = (name) => ({id:1, name:name});
  • 아래 5가지 모두 동일한 메소드다.
const obj1 = {
  log: function (value) {
    console.log(value);
  }
}

const obj2 = {
  log(value) {
    console.log(value);
  }
}

const obj3 = {
  log: (value) => {
    console.log(value);
  }
}

const obj4 = {
  log: (value) => console.log(value)
}

const obj5 = {
  log: console.log
}

Arrow Function vs function

  • 화살표 함수는 OOP에서 일부 기능(특히 상속 및 메서드 정의)에 적합하지 않습니다. 주로 콜백 함수나 간결한 표현이 필요한 상황에서 유용합니다. 화살표 함수는 this, super, arguments, new.target 같은 문맥적인 요소를 바인딩하지 않습니다. 특히, 객체의 메서드나 클래스 내 메서드를 정의할 때는 일반 함수 표현식이 더 적합합니다
  1. this 바인딩 생략: 화살표 함수는 자신만의 this를 가지지 않으며, 선언된 위치의 this를 상속받습니다. 따라서 this는 정적으로 바인딩됩니다.

  2. super 바인딩 없음: 클래스에서 사용하는 super를 바인딩하지 않습니다.

  3. arguments 바인딩 없음: 화살표 함수는 arguments 객체를 바인딩하지 않습니다. (arguments: 모든 인자에 접근할 수 있게 해주는 유사 배열 객체)

  4. prototype 속성 없음: 화살표 함수는 prototype 속성을 가지지 않으므로, 프로토타입 기반의 객체지향 패턴에서 사용할 수 없습니다.

  5. 생성자 함수 불가: 화살표 함수는 생성자 함수로 사용할 수 없으며, new 키워드를 사용할 수 없습니다.

Shorthand property names

const name = 'junha';
const age = '20';

const junha = {
  name,
  age 
};

const junha = { 
  name: name,
  age: age
}

Destructuring assignment

  • prop의 이름과 똑같이 설정할 경우
const car = { 
  name: 'Audi',
  age: '2019'
};

const { name, age:year } = car; // 동시에 rename 가능
name, year
// 'Audi', 2019
const animals = ['dog', 'cat'];
const [first, second] = animals;  // 작성한 순서에 따라 할당

first, second
// 'dog', 'cat'
  • 활용 예시
export const postAddMovie = (req, res) => {
  // 중략
   const movieObject = { title, synopsis, genresArray };
   addMovie(movieObject);
};

export const addMovie = ({ title, synopsis, genres }) => {
  // 중략
  movies = [{ id, title, synopsis, genres }, ...movies];
};
export const add = (req, res) => {
  // 중략
    const {
      body: { title, genres, synopsis }
    } = req;
};

nested destructuring

const obj1 = {
  title: "foo",
  child: {
    subTitle: "bar"
  },
};

const { title,  child : { subTitle }} = obj1
console.log(title,subTitle) // 'foo', 'subTitle'

4. Spread Syntax

  • ...을 붙여 프로퍼티들을 펼친다
const junha = {
    name: 'junha',
    age: '20',
    skill: 'js',
};

const junhaJunior1 = { ...junha}; 
const junhaJunior2 = { ...junha, skill: 'java' }; 
// spreadSyntax 도중 특정 프로퍼티의 값을 바꿀 수 있다.
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const concatArr = [...arr1, ...arr2];
// 두 배열의 요소를 합쳐 하나의 배열로 만들 수 있다.

객체 리턴 시 유의사항

  • 화살표 함수로 리터럴 오브젝트를 리턴할 때는 괄호로 감싸서 표현식으로 만들어줘야 한다.
data.map(item => ({...item, active: false}));

Rest operator를 이용한 배열 API 만들기

function arrayAPI(array) {
  
  function push(element) {
    return [...array, element];
  }

  function removeElement(index) {
    return [...array.slice(0,index), ...array.slice(index+1)];
  }

  function updateElement(index, element) {
    return [...array.slice(0,index), element, ...array.slice(index+1)];
  }

5. Rest Parameter

  • ...을 붙여 여러개의 인자들을 배열로 변환해 할당한다.
printAll('kim', 'junha', 'jjang');

function printAll(...args) {
    console.log(args); 
    //  ['kim', 'junha', 'jjang']
}
function sumArray(sum, ...arr) {
    if (arr.length === 0) 
        return sum;
    const [head, ...tail] = arr;
    return sumArray(sum + head, ...tail);
}
sumArray(0, 1, 2, 3, 4, 5);

6. Default Parameter

Before

function print(msg) {
    if (msg === undefined) {
        msg = 'default msg';
    }
    console.log(msg);
}

After

function print(msg = 'default msg') {
    console.log(msg);
}

print(); // default msg
print(0) // 0
  • Default parameter is only for undefined.
  • msg가 undefined인 경우에만 default msg가 할당된다.
function register(name, validator = (value) => true){
  ...
}
  • 함수도 default parameter로 받아올 수 있다.

7. template literals

1) ${boolean}

const boolean = true
const message = `hello ${boolean}`
console.log(message)
// 결과 : "hello true"

2) ${object}

const object = { a: "apple" }
const message = `hello ${object}`
console.log(message)
// 결과 : hello [object Object]
  • object는 바로 출력할 수 없다.

3) ${array}

const array = [1,2,3]
const message = `hello ${array}`
console.log(message)
// 결과 : hello 1,2,3

4) ${expression}: ternary operator

const name = "chalie"
const gender = "male"
const message = `Hello ${gender === "male" ? "Mr." : "Mrs."}${name}, nice to meet you`

console.log(message)
// 결과 : "Hello Mr.chalie, nice to meet you"

5) line break

document.body.innerText = `백틱은 줄바꿈이
지원된다.`
const textFromJs = ` 띄어쓰기도 지원되니 많관부   `
document.body.innerText = textFromJs

8. Optional Chaining (ES11)

?.

  • undefined, null의 속성에 접근하면 오류가 발생한다.
  • ?.을 사용하여, null 또는 undefined이면, undefined를 리턴
  • 그게 아니면 프로퍼티 값을 리턴한다.
const person1 = {
    name: 'junha',
    job: {
        title: 'Engineer',
        manager: {
            name: 'Bob',
        },
    },
};

const person2 = {
    name: 'yunjung',
    job:{
      title:"Cook"
    },
    action: {
      yelling() {
        console.log("YAYYY!")
      }
    }
};

function print(person) {
    console.log(person.job?.manager?.name);
}

print(person1); // Bob
print(person2); // undefined
person1.action?.yelling() // undefined
person2.action?.yelling() // YAYYY!

9. Nullish Coalescing Operator (ES11)

?? 연산자: null과 undefined 일 경우에만 작동한다

  • A || B는 A가 falsy한 값인 경우 B를 반환했다.
  • A ?? B는 A가 null, undefined인 경우에만 B를 반환한다.
  • null, undefined를 제외한 falsy 값을 그대로 리턴하고 싶은 경우 사용한다.
  • falsy: false로 반환하는 값: '', 0, -0, null, undefined, NaN
const obj = {
    0: false,     // false : false
    1: '',        // : 
    2: 0,         // 0: 0
    3: null,      // null : Nullish Coalescing
    4: undefined, // undefined : Nullish Coalescing
    5: NaN,       // NaN : NaN
};

for (let key in obj) {
    console.log(`${obj[key]}: ${obj[key] ?? 'Nullish Coalescing'}`);
}
  • leftExpr() ?? rightExpr() 형태이기 때문에, const result = func1() ?? func2()도 가능하다.

10. !! double exclamation mark

  • 변수에 값이 할당되어있으면 true, 그렇지 않으면 false로 반환해준다.
  • data가 valid한지 boolean으로 바꿔주는 표현식이다.
  • 이는 연산자가 아니라, not을 두번한 것으로, !falsy value 값이 true를 반환하는 점을 이용한 논리다.
!3          // false
!"string"   // false
![]         // false
!0          // true
!null       // true
!falsyValue // true
!!3          // true
!!"string"   // true
![]         // true
!!0          // false
!!null       // false
!!falsyValue // false
const isLoggedIn = !!getUserInfo();

Quiz

  • Remove duplicates ['a','a','b','b','c','d','e'] and return as an array.
const arr = ['a', 'a', 'b', 'b', 'c', 'd', 'e'];
const answer = [...new Set(arr)];
console.log(answer);