Talking about JavaScript (1) – The difference between Function Declarations and Function Expressions

Tram Ho

Compare Function Declarations and Function Expressions

Article Objectives:

Helps you better understand javascript and know when to use one way, when to use another.
Avoid being claim when reviewing code.

Concepts you need to understand before reading further.

  • Hoisting in javascript Hoisting is also a different part of javascript that is different from other programming languages.

You try to read it, if you have any questions, you can comment below the article with me.

** OK, now let’s go! **🔢

Well, if you do not know what Function Declarations are and what Function Expressions are, let me give you a hint.
I’m sure you’ve written it before but can forget it and not know what to call it

1. Function Declarations

This declaration is known by everyone

2. Function Expressions

With this declaration:

  • Your entire function statement will be stored in the test variable.
  • Your function also doesn’t need a name, as it will be called through the test variable.

So what is the difference between these two types of declaration?

  1. Function Declarations always have priority to load first. Function expressions it will load in the correct order, when the compiler runs to that line, it will load.
  2. Similar to variables declared with var, declarations function is also hoisted above other code, and Function expressions are not hoisting.

See the following example to understand better.
You should not get any errors when you execute the function call even before the code initializes the function.
The reason is that the compiler implicitly moved the test function declaration up before the function was called.

As for the example below you will obviously eat an error because it cannot find the test function at the time you call it.

Hope here you also understand.

So when to use Function Declarations and when to Function Expressions.

In my opinion: I often use Function Declarations when I want to turn those functions into global form, which can be called anywhere.
And Function Expressions are used in cases such as:

  1. Want to use that function passed to another function (callback for example)
  2. When we want to use it as a closure
  3. … a few other cases I don’t remember, ask you to comment for me.

Combining using Function Expressions instead of always Function Declarations will make your code cleaner and more controllable.

Thank you for reading here.
Above is what I understand, there may be incorrect places.
Looking forward to hearing from you …
Thanks!

Share the news now

Source : Viblo