Introduction
Functions are an essential part of programming. Javascript provides two ways of creating functions: function definition and function declaration. Sadly, both concepts tend to be misunderstood. Understanding both concepts will help you become a better Javascript developer .
// Function 1
function func1(){
console.log("starting app");
}
// Function 2
const func2 = () =>{
console.log("starting app");
}
Take a moment to examine the code above. If you're like me, you might recognize one syntax as "old" and the other as "new". Which, of course, is not entirely wrong. The syntax on the left is known as function declaration while the other is known as function definition.
Function declaration and function definition are not exactly the same. Javascript does not follow the traditional top-down approach when we define a function. It places our function at the top of the call stack. What does this mean? It means you can call a function even before it is created!
Example
// function definition example
greet();
const greet = () => {
console.log("Stay safe");
}
The above code returns an error. This is because the function was called before it created.
// function declaration example
greet();
function greet(){
console.log("Stay safe");
}
Wow, the code works! this is because the function was placed at the top of the call stack. That's what happens when we declare a function.
Summary
Function declaration and function definition are both valid ways of writing functions in Javascript. The choice is all yours!
Stay safe :)