함수 (Function)

7.1 함수 선언 대신 명명된 함수 표현식을 사용한다.

함수 선언은 호이스팅 된다. 그렇기 때문에 코드 가독성과 유지보수에 피해를 줄 수 있다.

// bad
function foo() {
  // ...
}

// bad
const foo = function () {
  // ...
};

// good
// 이렇게 했을 때 오류상황에서 디버깅 용이?
const short = function longUniqueMoreDescriptiveLexicalFoo() {
  // ...
};

7.2 즉시 실행 함수 표현식을 괄호로 묶는다.

// immediately-invoked function expression (IIFE)
(function () {
  console.log('Welcome to the Internet. Please follow me.');
}());

7.3 함수를 절대 non-function block (if, while, etc) 안에 선언 하지 마라

https://eslint.org/docs/rules/no-loop-func.html

// bad
for (var i = 0; i < 10; i++) {
    funcs[i] = function() {
        return i;
    };
}

// good
var foo = 100;
for (let i=10; i; i--) {
    var a = function() { return foo; }; // OK, all references are referring to never modified variables.
    a();
}
//...

7.4 ECMA-262에서 block은 statements 목록에 정의되지만, 함수 선언은 statements가 없다.

// bad
if (currentUser) {
  function test() {
    console.log('Nope.');
  }
}

// good
let test;
if (currentUser) {
  test = () => {
    console.log('Yup.');
  };
}

7.5 매개변수에 arguments를 절대로 지정하지 않는다. 이것은 함수 영역으로 전달 될 arguments객체의 참조를 덮어 써 버릴 것이다.

// bad
function foo(name, options, arguments) {
  // ...
}

// good
function foo(name, options, args) {
  // ...
}

7.6 arguments를 사용하지 않는다. 대신 레스트(Rest) 문법인 ...을 사용해라.

// bad
function concatenateAll() {
  const args = Array.prototype.slice.call(arguments);
  return args.join('');
}

// good
function concatenateAll(...args) {
  return args.join('');
}

7.7 인자의 초기 값을 지정 할 때

// really bad
function handleThings(opts) {
  // No! We shouldn’t mutate function arguments.
  // Double bad: if opts is falsy it'll be set to an object which may
  // be what you want but it can introduce subtle bugs.
  opts = opts || {};
  // ...
}

// still bad
function handleThings(opts) {
  if (opts === void 0) {
    opts = {};
  }
  // ...
}

// good
function handleThings(opts = {}) {
  // ...
}

7.8 부작용이 있는 기본 매개변수를 사용하지 않는다.

var b = 1;
// bad
function count(a = b++) {
  console.log(a);
}
count();  // 1
count();  // 2
count(3); // 3
count();  // 3