Reputation: 24602
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?
Upvotes: 3
Views: 1926
Reputation: 34117
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/
Upvotes: 1
Reputation: 94131
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.
Upvotes: 0
Reputation: 225263
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.
}
}
}();
Upvotes: 3