Javascript Functionname Function vs Function Functionname
Learn when we use var functionName = function() {} vs function functionName() {}
Published
Function declaration can be achieve in several ways and all valid. However, there are differences on how they’re handled in the background.
A simple way to declare a function
Syntax function functionName([parameters]){functionBody};
function sum(a, b)
{
return a+b;
}
alert(sum(5,4)); // result: 9
When we declare function like this, the content of the function is compiled (but not executed until we call the function). Also, you might not know it, but an object with the same name as the function is created. In the above example, we have an object named “add” (for more on this, see Function as an Object section below.)
Function Declaration using unnamed function to a variable
We can also declare a function by assigning a variable to an unnamed function.
var add = function(a, b)
{
return a+b;
}
alert(sum(5,4)); // result: 9
This code does the same thing as the previous example. The syntax may seem odd, but it may make more sense when you consider that a function is an object, and we’re just assigning a name to the object. Think of it as saying var myVar=[1,2,3]; The content of functions declared this way is also compiled.
The ability to declare function in this way is useful in object oriented programming, because we can have a function be a property of an object, like this.
var myObject=new Object();
myObject.add=function(a,b){return a+b};
myObject.add(1, 2);
Please note: myObject now has a property/a method named “add”. So, we can use it like myObject.add(1, 2);