Hello fellow developers out there,
I have this question which my colleagues don't seem to reach an agreement about.
Considering JS hoisting and that functions expressions are not called when the component mounts, it seems to be safe to assume we are not going to have any problems by declaring methods violating "used before it was defined".
But I wonder if is it safe to ignore lint's warnings about it and declare component's functions alphabetically or according to logic blocks or whatever...? Even though if a function declared first calls another one declared later?
For example (this is just a simplification of a large functional component with lots of functions where it would be really hard for another developer to get organized around all of it):
const SomeRandomFC = () => {
// User logics
const changeUser = id => {
if (id !=== currentId) {
getDatabase(id);
}
const getUser = id => ...
// Database logics
const getDatabase = user => [fetch logics];
const updateDatabase = id => ...
}
Thanks!
Leaving opinion aside, let's say you have:
const a = () => {
b();
};
// a(); // <== Would fail
const b = () => {
// ...
};
a(); // <== Works
From a "does it work" perspective, the call at the end there is fine, because by the time that call occurs, b
has been initialized. However, if you uncommented the first call to a
above, it would fail because b
hasn't been initialized yet.
You mentioned hoisting. Beware that since you're using function expressions assigned to constants instead of function declarations, only the declaration of the constant is hoisted, not the initialization of that constant. In contrast, if you have a function declaration, both the declaration of its binding and the initialization of that binding are hoisted:
function a() {
b();
}
a(); // <== Works
function b() {
// ...
}
a(); // <== Works
Note that the call that would have failed in the first example works in the second one.
(Please don't take this as a suggestion to use function declarations instead. It isn't. I'm just pointing out the difference in behavior.)
Whether you use constants with function expressions or function declarations, the order in which you lay out your functions is up to you and your team, provided you don't have a situation like the commented-out call to a
in the first code block above.