함수 선언은 호이스팅 된다. 그렇기 때문에 코드 가독성과 유지보수에 피해를 줄 수 있다.
// bad
function foo() {
// ...
}
// bad
const foo = function () {
// ...
};
// good
// 이렇게 했을 때 오류상황에서 디버깅 용이?
const short = function longUniqueMoreDescriptiveLexicalFoo() {
// ...
};
// immediately-invoked function expression (IIFE)
(function () {
console.log('Welcome to the Internet. Please follow me.');
}());
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();
}
//...
// bad
if (currentUser) {
function test() {
console.log('Nope.');
}
}
// good
let test;
if (currentUser) {
test = () => {
console.log('Yup.');
};
}
// bad
function foo(name, options, arguments) {
// ...
}
// good
function foo(name, options, args) {
// ...
}
// bad
function concatenateAll() {
const args = Array.prototype.slice.call(arguments);
return args.join('');
}
// good
function concatenateAll(...args) {
return args.join('');
}
// 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 = {}) {
// ...
}
var b = 1;
// bad
function count(a = b++) {
console.log(a);
}
count(); // 1
count(); // 2
count(3); // 3
count(); // 3