yqlim
yqlim

Reputation: 7080

Since function expression and function declaration basically do the same thing, when should I use which?

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.

Upvotes: 0

Views: 46

Answers (2)

afuous
afuous

Reputation: 1498

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.

Upvotes: 0

Thilo
Thilo

Reputation: 262474

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.

Upvotes: 1

Related Questions