Preventing hoisting and scope errors
- Avoid using
var
to declare variables, whenever possible. - Use
const
to declare variables, unless the variable needs to be reassigned. If the latter is true, uselet
. - Clean code: declare the variables at the top of each scope.
- Clean code: declare functions before using them.
- Don't use arrow functions as methods, because the
this
keyword will point to the parent function/object, and not to the object calling the method. Always use function declarations.
- We should use functions instead of writing code directly on the global scope, and pass variables to functions as arguments instead of using global variables.
- It's a bad practice to mutate function parameters, so when a parameter needs to be modified inside a function, it's better to create a copy of that parameter and modify that copy.
- It's a bad practice to chain methods that mutate the original array, such as the
splice()
method. - If there is a variable that we must define but is not going to be used, we should name it
_
:
const myArr_4 = Array.from({ length: 7 }, (_, i) => i + 1);
console.log(myArr_4);
// -> [1, 2, 3, 4, 5, 6, 7]