JavaScript Fundamentals - Function declaration vs Function expression

- 2 mins

Index


Series contents


Introduction

Functions are the most important building block of JavaScript. It isolates sections as well as reduce task repitation. There are two waus to use functions in JavaScript.

Using function declaration and using function expression.


Function declaration and Function expression

The syntax for function declaration is

    function hello(){
        console.log("Hello World!")
    }

    hello(); //Hello World!

and the syntax for function expression is

    const hello = function(){
        console.log("Hello World!")
    }

    hello(); //Hello World!

Both syntax generates similar output. Then why both exists?


Difference between Function declaration and Function expression

Although both statements shows similar output, they’ve a key difference.

The Function declaration is sort of global declaration. Whenever a JavaScript script run, it looks for global declarations (here the Function declaration) and creates them. After that the code is executed.

So a Function declaration can be called before writing it into the code.

    hello(); //Hello World!

    function hello(){
        console.log("Hello World!")
    }

It won’t throw any error.

But in case of Function expression it created when script execute and reaches to it’s line. After that it is available in the code. So like Function declaration if it is called earliar in the code, we will see an error message-

    hello(); //Uncaught ReferenceError: Cannot access 'hello' before initialization

    const hello = function(){
        console.log("Hello World!")
    }

So what’s the benefit?

In a large script, when there is a function that requires later execution, we can declare it as a Function expression. In that way, whenever, JavaScript engine runs the script, it won’t have to create the function and keep it in the call stack and carry for later use.


comments powered by Disqus
rss facebook twitter github youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora