Home var functionName = function() {} vs function functionName() {}
Reply: 0

var functionName = function() {} vs function functionName() {}

user10826
1#
user10826 Published in September 19, 2018, 6:44 pm

I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features, and also trying to tidy up the code and make it more consistent.

The previous developer uses two ways of declaring functions and I can't work out if there is a reason behind it or not.

The two ways are:

var functionOne = function() {
    // Some code
};
function functionTwo() {
    // Some code
}

What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other?

share|improve this question
  • 183
    permadi.com/tutorial/jsFunc/index.html is very good page about javascript functions – uzay95 Apr 9 '10 at 11:51
  • 62
    Related is this excellent article on Named Function Expressions. – Phrogz Apr 21 '11 at 21:30
  • 11
    @CMS references this article: kangax.github.com/nfe/#expr-vs-decl – Upperstage Aug 3 '11 at 14:18
  • 93
    There are two things you need to be aware of: #1 In JavaScript, declarations are hoisted. Meaning that var a = 1; var b = 2; becomes var a; var b; a = 1; b = 2. So when you declare functionOne, it gets declared but its value isn't set immediately. Whereas since functionTwo is just a declaration, it gets put at the top of the scope. #2 functionTwo lets you access the name property and that helps a lot when trying to debug something. – xavierm02 Aug 21 '12 at 16:20
  • 57
    Oh and btw, the correct syntax is with a ";" after the assignation and without after the declaration. E.g. function f(){} vs var f = function(){};. – xavierm02 Aug 21 '12 at 16:27

33 Answers 33

active oldest votes
1 2 next
up vote 4544 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.715074 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO