I'm having a bit of trouble understanding why my code works. I'm expecting a reference error, but everything works fine.
My code:
const functionA = () => {
let bResult = functionB();
console.log("Function A " + bResult);
};
const functionB = () => {
return "Function B";
};
functionA();
I get this output (no errors);
λ node test.js
Function A Function B
As I understand it, only function declarations are hoisted (not function expressions) http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.html.
Thus, shouldn't I expect an error as FunctionB isn't defined before it's called in FunctionA? Am I missing somewhere here?
EDIT: Thanks for the answers everyone, I think I figured it out. It's indeed not getting hoisted because if I call functionA at the beginning, it gives me an error.
functionA(); // ReferenceError: functionA is not defined
const functionA = () => {
let bResult = functionB();
console.log("Function A " + bResult);
};
const functionB = () => {
return "Function B";
};
So it's not a question of hoisting. Rather, by the time functionA is called at the end of the file, both functionA and functionB have been defined.
functionA
is actually executed,functionB
will be set. So this works just fine. It would be terribly annoying if you had to define all of your functions "in order". Not to mention, mutual recursion depends on this behavior. – MorphogenesisfunctionB
is set, but it's referred to infunctionA
before it's defined. Why doesn't it need to be defined in advance given that it isn't hoisted – Enhancedconst functionA = () => {..}; functionA(); const functionB = () => {..}
– Pozsonyvar
, so this might be more useful var vs. let – NeumarkfunctionB
is hoisted and the identifier is available immediately. However, the value forfunctionB
is not ready to use untilfunctionB
is actually defined. Adiga's comment about runningfunctionA()
before thefunctionB = ...
will show the "problematic" behavior. – Morphogenesisconst
declaration is hoisted as well, since the article (pre-ES6) only talks aboutvar
being hoisted. – CarolinianfunctionA
which is a function is created. The contents of it are irrelevant because they are not actually run until it's called. Then another variable calledfunctionB
is created. ThenfunctionA
is executed. Inside it, a function calledfunctionB
is sought and it is actually available in the scope. So, it's executed. – Pozsony