0

As the question suggest, when should I use

Example A (function declaration):

function abc(){ // some code } abc(); 

over Example B (function expression):

var abc = function(){ // some code } abc(); 

and vice versa.

I know they are different in nature but they basically just do the same thing (correct me if they're not), right?

So how to I decide which one should I use?

EDIT :

I know for Example A, the function can be called whenever wherever intended due to hoisting.

What I actually want to know is what makes you decide to use Example A or Example B.

5
  • The variable version cleanable and must be defined before calling the other one is not. that as my knowledge. Commented Nov 8, 2016 at 4:16
  • you would need the var abc = function() declaration, when you need to pass your function as a callback to any other function. Commented Nov 8, 2016 at 4:17
  • 2
    @JerinJoseph both of them support this feature. Commented Nov 8, 2016 at 4:20
  • 1
    Possible duplicate of JavaScript function declaration syntax: var fn = function() {} vs function fn() {} Commented Nov 8, 2016 at 4:26
  • @Thilo I didn't find an answer there. which is why i decided to ask a new question. Thanks for pointing that out tho! Commented Nov 8, 2016 at 5:33

2 Answers 2

1

If you want to call abc() before defining the function, only the first pattern will work.

The variable declaration does get hoisted, too, but not the assignment, so it will be undefined, whereas the function will already be complete with its body.

I guess I would use the var pattern only if I intend to re-assign it later.

Sign up to request clarification or add additional context in comments.

Comments

0

Generally, you should use the function declaration syntax when possible. The best reason is that if you define the function in the code after its use, the code will still work.

stuff(); function stuff() { console.log("hello"); } 

will work, but

stuff(); var stuff = function() { console.log("hello"); } 

will not.

When you are passing an anonymous function to another function, you use a function expression.

doSomething(function() { console.log("done"); }); 

Otherwise, both work.

2 Comments

Hi, so basically one doesn't need to use function expression unless you need to pass an anonymous function?
@YongQuan Yes. Usually it can only be worse.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.