Skip to content

String (문자열)

🧩 Note

문자열은 데이터 표현에서 가장 기본적인 타입 중 하나지만,
Airbnb 가이드에서는 일관된 따옴표 규칙과 템플릿 리터럴 사용을 통해 가독성과 유지보수성을 강조한다.

1. 문자열에는 작은 따옴표 ''를 사용

eslint: quotes

js
// bad
const name = 'Capt. Janeway';

// bad - 템플릿 리터럴은 "${}" 보간이나 줄바꿈이 있을 때만 사용
const name = `Capt. Janeway`;

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

2. 100자가 넘는 문자열을 여러 줄로 끊지 않는다.

js
// 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.';
  • 문자열이 끊어지면 작업하기 어렵고, 코드를 찾기 어렵게 된다.
  • 줄바꿈 필요 시 템플릿 리터럴을 사용하는 것이 낫다.

3. 문자열 결합 시 +(문자열 연결) 대신 템플릿 문자열 사용

eslint: prefer-template, template-curly-spacing

js
// 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}?`;
}
  • 템플릿 리터럴은 변수 보간과 줄바꿈을 지원하므로 가독성과 유지보수성이 높다.

4. 문자열에 eval()을 사용하지 않는다.

  • eval()은 문자열을 코드로 실행하므로 보안상 매우 위험하다.
  • XSS, 코드 인젝션 등 치명적 취약점을 유발할 수 있다.

5. 불필요한 \(이스케이프 문자)를 사용하지 않는다.

eslint: no-useless-escape

js
// bad
const foo = '\'this\' is "quoted"';

// good
const foo = '\'this\' is "quoted"';
const foo = `my name is '${name}'`;
  • 백슬래시는 가독성을 떨어뜨리므로 필요할 때만 사용해야 한다.
  • 템플릿 문자열을 활용하면 불필요한 이스케이프를 줄일 수 있다.