Problem Statement
Can you call a function declaration before it is defined in the code?
Explanation
Yes, you can call a function declaration before it is defined because of hoisting.
JavaScript moves the entire function declaration including its body to the top of the scope during compilation.
This is different from function expressions and arrow functions which are not hoisted in the same way.
Function declarations are fully available throughout their scope. This behavior is useful but can lead to confusion, so many developers prefer to define functions before using them for better readability.
Code Solution
SolutionRead Only
// Function declaration - can call before definition
greet(); // Works! Prints 'Hello'
function greet() {
console.log('Hello');
}
// Function expression - cannot call before definition
// sayBye(); // TypeError: sayBye is not a function
let sayBye = function() {
console.log('Bye');
};
// Arrow function - cannot call before definition
// welcome(); // ReferenceError
const welcome = () => {
console.log('Welcome');
};
// Why function declaration works
function calculate(a, b) {
return a + b;
}
// JavaScript sees it as:
// Function moved to top, then code runs
console.log(calculate(5, 3)); // 8