Move function declaration to function body root.
3326
3327 // equations of right and left sides, returns x, y values given height of section (y value and 2 points)
3328
3329 function findedge (l, p1, p2) { 3330 const m = (p1[1] - p2[1]) / (p1[0] - p2[0]) 3331 const b = p1[1] - m * p1[0] 3332 const y = l + p1[1] 3333 3334 return [(y - b) / m, y] 3335 } 3336
3337 // check each section
3338 lex = findedge(y, vfirst[0], vlast[3])
Description
Function declarations (with the function
keyword) and variable declarations should preferably be in the root of a program or the body of a function.
Having nested function declarations inside blocks may have unexpected results at runtime due to hoisting.
As a rule of thumb, if you ever find yourself needing to use nested functions:
Prefer
const f = () => ...
overfunction f() {...}
for functions inside block-statements.When using
function
orvar
, do not have any declarations that can possibly be accessed outside the block in which they're declared.
Note: Block bindings (let
, const
) are not hoisted and therefore they are not affected by this rule.
Bad Practice
function outer(test) {
if (test) {
// the declaration for "inner" can
// be accessed outside the if-statement
// only when `test` is truthy.
function inner() {
return "inner value";
}
inner();
}
// works only if `test` is true.
return inner();
}
outer(true); // "inner value"
outer(false); // TypeError: inner is not a function
Recommended
inner
should be moved out of the if
block, or be declared with a const
keyword.
// When `inner` is needed outside the `if` block:
function outer(test) {
const inner = () => "inner value"
if (test) {
inner();
}
// always works.
return inner();
}
// When `inner` is not needed outside the `if` block:
function outer(test) {
if (test) {
const inner = () => "inner value"
inner();
}
return "outer value"
}