Airbnb JS Guide

서성원·2024년 10월 17일
0

자바스크립트

목록 보기
4/6
post-thumbnail

에어비엔비 JS가이드를 참고하여 우테코 프리코스에 사용할 js 스타일 가이드를 정리했다. 계속 업데이트 예정..!

1. Reference

참조 시 var보단 const를 사용한다.

✨예시 코드

// bad
var a = 1;
var b = 2;

// good
const a = 1;
const b = 2;

재할당이 필요할 시 let을 사용한다.

✨예시 코드

// bad
var count = 1;
if (true) {
  count += 1;
}

// good, use the let.
let count = 1;
if (true) {
  count += 1;
}

변수 스코프 정리

// const and let only exist in the blocks they are defined in.
{
  let a = 1;
  const b = 1;
  var c = 1;
}
console.log(a); // ReferenceError
console.log(b); // ReferenceError
console.log(c); // Prints 1
  • letconst: 블록 내에서만 유효하다.
  • var: 함수 내에서만 유효하지만, 블록을 벗어나도 여전히 접근 가능하다.

2. Strings

문자열은 ' ' (작은 따옴표)를 사용한다.

✨예시 코드

// bad
const name = "Capt. Janeway";

// bad - template literals should contain interpolation or newlines
const name = `Capt. Janeway`;

// good
const name = 'Capt. Janeway';

100자가 넘지 않는 문자열을 다음 라인으로 넘기지 않는다.

✨예시 코드

// bad
const errorMessage = 'This is a super long error that was thrown because \
of Batman. When you stop to think about how Batman had anything to do \
with this, you would get nowhere \
fast.';

// bad
const errorMessage = 'This is a super long error that was thrown because ' +
  'of Batman. When you stop to think about how Batman had anything to do ' +
  'with this, you would get nowhere fast.';

// good
const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';

문자열을 결합할 때는 ${}로 감싼 템플릿 리터럴을 사용한다.

✨예시 코드

// bad
function sayHi(name) {
  return 'How are you, ' + name + '?';
}

// bad
function sayHi(name) {
  return ['How are you, ', name, '?'].join();
}

// bad
function sayHi(name) {
  return `How are you, ${ name }?`;
}

// good
function sayHi(name) {
  return `How are you, ${name}?`;
}

3. Arrays

배열 만들 시 리터럴을 사용한다.

✨예시 코드

// bad
const items = new Array();

// good
const items = [];

추가할 땐 push

✨예시 코드

const someStack = [];

// bad
someStack[someStack.length] = 'abracadabra';

// good
someStack.push('abracadabra');

iterable 객체를 배열로 변환하기

✨예시 코드

const foo = document.querySelectorAll('.foo');

// good
const nodes = Array.from(foo);

// best
const nodes = [...foo];

4. Functions

함수선언 vs 함수 표현식

✨예시 코드

// bad
function foo() {
  // ...
}
  • 함수선언

함수 선언은 호이스팅된다. 즉, 어느 곳에서 정의했든 상관없이 파일 내에서 호출할 수 있다.

하지만 호이스팅은 파일 흐름을 이해하기 어렵게 만들고, 함수가 정의되기 전에 참조될 우려가 있어 가독성과 유지보수 측면에서 좋지 않다.

✨예시 코드

// bad
const foo = function () {
  // ...
};
  • 익명함수 표현식

함수표현식은 호이스팅되지 않는다. 즉, 함수가 정의되기 전에는 참조할 수 없어 유지보수측면에서 좋다.

하지만 함수에 이름이 없어 디버깅 시 에러스택에 함수 이름이 나타나지 않아 문제를 추적하기 힘들다.

✨예시 코드

// good
// lexical name distinguished from the variable-referenced invocation(s)
const short = function longUniqueMoreDescriptiveLexicalFoo() {
  // ...
};
  • 이름이 있는 함수표현식

함수표현식에 이름을 부여해 함수가 디버깅 시 콜스택에서 추적할 수 있도록 한다.

함수표현식이므로 호이스팅되지 않아 코드 흐름이 간결해진다.

블록 내에서 함수를 사용하지 않는다.

✨예시 코드

// bad
if (currentUser) {
  function test() {
    console.log('Nope.');
  }
}
  • ECMAScript(ECMA-262) 표준에 따르면 블록은 문장에 포함된다.
    하지만 함수선언은 문장이 아니다. 이로 인해 생기는 문제점에는 호이스팅 되지 않음, 제대로 정의되지 않음 등이 있다.

✨예시 코드

// good
let test;
if (currentUser) {
  test = () => {
    console.log('Yup.');
  };
}
  • 함수표현식을 사용해 변수를 할당하는 방식이 권장된다.
  • 이것은 블록 내에서 안전하게 사용가능하고, 호이스팅 문제가 발생하지 않는다.

함수 서명(function signature)에서의 공백사용

✨예시 코드

// bad
const f = function(){};  // 문제: 괄호와 중괄호 사이에 공백이 없음
const g = function (){}; // 문제: 중괄호 앞에 공백이 없음
const h = function() {}; // 문제: 괄호 앞에 공백이 없음

// good
const x = function () {};  // 괄호와 중괄호 앞에 각각 공백을 둠
const y = function a() {}; // 함수 이름이 있어도 공백 처리가 일관됨
profile
FrontEnd Developer

0개의 댓글

관련 채용 정보