I use the "Lazy Function Definition" pattern to define global functions like so:
if (bArmingSequenceComplete () ) {
console.log ("Good to go.");
}
// Code flows from high level to low level and support functions...
// vvvvv
function bArmingSequenceComplete () {
// In reality this is a long, complicated series of tests that only need to be done once.
var gtg = true;
if (gtg) {
bArmingSequenceComplete = function () { return true; };
}
else {
bArmingSequenceComplete = function () { return false; };
}
return bArmingSequenceComplete ();
}
This works flawlessly and the overall code is easy to grok.
I like this pattern because it's very efficient AND it's clear as to what it's doing.
But JSHint gives me warnings like:
Reassignment of 'bArmingSequenceComplete', which is is a function. Use 'var' or 'let' to declare bindings that may change.
After diving into some JSHint source code, I found that this is controlled by the W021
option. So I can squelch it like:
// jshint -W021
if (gtg) {
bArmingSequenceComplete = function () { return true; };
}
else {
bArmingSequenceComplete = function () { return false; };
}
// jshint +W021
But, is JSHint telling me something useful? Is it really a mistake to define such functions?
Can I disable all such warnings globally without also losing the general "Reassignment" check?
The suggestions to use let
or var
make for worse code (violates "Most important at top" rule and/or completely fails).
For example:
if (bArmingSequenceComplete () ) {
console.log ("Good to go.");
}
// Code flows from high level to low level and support functions...
// vvvvv
let bArmingSequenceComplete = function () {
...
Fails with:
Uncaught ReferenceError: bArmingSequenceComplete is not defined
And:
if (bArmingSequenceComplete () ) {
console.log ("Good to go.");
}
// Code flows from high level to low level and support functions...
// vvvvv
var bArmingSequenceComplete = function () {
...
Fails with:
Uncaught TypeError: bArmingSequenceComplete is not a function
Defining the function before use, violates the boss's "most important or high-level up top" rule.