2

When I run a function in js it seems to work fine but will this be fine?

function myfunction(){ }

VS

var myfunction = function(){ }

Because both are called the same so does it make no difference? Sorry new to js so i'm just making sure it's good to learn this style. (The first function is what i'd prefer to use.)

Vince
  • 39
  • 4

2 Answers2

1

As shown in the W3Schools Function guide

You can use a function declaration or a function expression.

Both are the same in general. Thought there are certain things to consider:

  • In a function expression the function is only defined when that line in code is reached
  • In a function decleration the function is defined as soon as the code is run, so it can be called before it is written in your code (due to hoisting)

The first example you wrote is a function Declaration

The second example you wrote is a function Expression

The only difference between the two is how you will invoke them in your code after you defined them.

If you are wondering which is better, it all comes down to which you are more comfortable with and think the syntax for is more readable, also try not to mix up the two to keep conventions in your code.

Mor Paz
  • 1,949
  • 2
  • 14
  • 33
1

This question is already asked at this link, One of the basic difference comes from declaration, for instance :-

foo();
var foo = function(){
console.log('hi');
}

would lead to undefined, since it is called before it's declared, on the other hand,

foo();
function foo(){
console.log('hi');
}
would console 'hi' with no problem, for further insight check the above link.
Community
  • 1
  • 1
slapbot
  • 457
  • 1
  • 4
  • 15