❗function in block (FiB)
a "function declaration" defined in a "block".
JS ⟩ declaration ⟩ function ⟩ function in block (FiB)
Don't use function (declaration) in block❗
a function declaration defined in a block.
sloppy mode: hoisted / initialized to undefined (outside block)
strict mode: local to the block.
JS spec says that "function declaration in block is block-scoped" ❗
However, in most browser-based JS engines (including v8):
the identifier of the FiB is scoped outside the block
function (declaration) in block
in sloppy mode:
can be considered as a redeclaration
if there's already a function with the same name in the outer scope
the (re)assignment is not applied until the block is run❗
in strict mode:
is local to the block❗
never is a redeclaration any more❗
👉 compare: var
recommendations for function in block (FiB)
don't use it❗
replit:pure FiB
// 'use strict'; // ⭐️ toggle sloppy/strict mode
// undeclared; // ⛔ ReferenceError: 'undeclared' is not defined
// ❗ access before declaration
console.log(pureFiB === undefined);
// • sloppy: ✅ true
// • strict: ⛔ ReferenceError: 'pureFiB' is not defined
// block
{
// ⭐️ "pure" function in block
function pureFiB() {
console.log(`I'm "Pure FiB".`);
}
}
// ❗ "function in block" has no "block scope"
// -----------------------------------------------
// • sloppy: ✅ hoisted / initialized to undefined (in outer scope)
// • strict: ⛔ ReferenceError (invisible in outer scope)
pureFiB();
// • sloppy: ✅ I'm "Pure FiB".
// • strict: ⛔ ReferenceError: 'pureFiB' is not definedLast updated
Was this helpful?