3

In my code I have the following:

var setTheme = function (color) {

};

function setTheme(color) {

};

The function names are not really the same but I have put the same here. Is there a difference in the two ways of creating a function?

ajax333221
  • 10,585
  • 14
  • 56
  • 89
Alan2
  • 19,668
  • 67
  • 204
  • 365
  • have a look at it. http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname – Karesh A Jul 05 '12 at 03:38
  • The first method is often used as callback functions. This is mainly to control the order of function execution. – itsols Jul 05 '12 at 03:54

3 Answers3

3

There is a difference. With a function definition, the entire definition is hoisted:

foo(5); // Pops up 5

function foo(n) {
    alert(n);
}

Whereas with var, the declaration is hoisted but the assignment is not:

foo(5); // Error!

var foo = function(n) {
    alert(n);
};

Another difference I noticed is that on Google Chrome Canary (currently and at least, I haven't tried in many other browsers) in ECMAScript 5 strict mode, a function definition cannot be nested more than one level deep:

!function() {
    'use strict';

    function Blah() {
        function Lol() { // Error.
        }
    }
}();
Ry-
  • 199,309
  • 51
  • 404
  • 420
1

So,

JS function for get set

    var setTheme = function (color) {

    };

If you need a private utility for getting/setting/deleting model values then you can declare a function as a variable like this. This could be useful for assigning a variable upon declaration calculated by a function.

For: simple version

function setTheme(color) {

};

This is the simplest way to declare a function in JavaScript. Say for example, we want to write a simple function called setTheme(color) which simply takes in one parameter color, does a simple color on the object or returns the value. Here are a few ways you might go about doing exactly this.

5 Different ways: interesting read:

http://www.jquery4u.com/jquery-functions/5-ways-declare-functions-jquery/

Tats_innit
  • 33,101
  • 9
  • 67
  • 75
0

This has been answered many times. There are many ways to call these. As I understand, the first one is a function assignment, the second one is a function declaration. The first one will hoist setTheme to the top of the closest scope but it won't be defined as a function till it gets where it's actually assigned. The second one will hoist the function setTheme up top so you'll be able to use this function even before it's been declared. IMO, use always the first one.

elclanrs
  • 85,039
  • 19
  • 126
  • 159