Function Declaration vs Function Expression in JavaScript

There are different ways to define a function in javascript. I have seen these 2 ways to define and get confused with the differences then I googled and came across with some points which can help out to others to understand the difference between these.

Function Declaration vs Function Expression in JavaScript

The two ways are:

The difference is that ‘functionOne‘ is defined at run-time, whereas functionTwo is defined at parse-time for a script block. For example:

It will show the error because functionOne is defined later than the calling.

In Strict mode, We can’t conditionally define functions using the second syntax:

Without “use strict” this would not cause an error and functionOne will be defined irrespective of condition’s value.

If you want to alias functions on all browsers use this kind of declaration:

In this case both xyz and abc are aliases of the same object.
Basically when we define a function like this:

its name is automatically assigned. But when you define it like this:

its name is empty — we created an anonymous function and assigned it to some variable.

abc name is automatically assigned and assigned to a variable xyz like alias. so It prints “abc”.

So it is basically a difference between function declaration and function expression.

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.