I often notice web developers misunderstanding the syntax of JavaScript functions. Even after a few years of experience. It can be a bit difficult to understand the different ways in which you can implement functions. Take a look at the following code.function addOne(val) {
return val + 1;
}
var addTwo = function(val) {
return val + 2;
};
window.addThree = function(val) {
return val + 3;
};
window["addFour"] = function(val) {
return val + 4;
};
All of these will work. The first declaration, for addOne, is usually the most familiar. It is pretty straight-forward. The declaration of addTwo achieves the same end result. You start by defining a variable, addTwo. Then you set addTwo equal to a function. In both cases you end up with a variable which are set equal to a function.
With addThree we are setting window.addThree equal to a function. In reality, window.addOne and window.addTwo are already set as well. You can think of window as the root object in which all else stem from.
The declaration of addFour is virtually the same as addThree except that you are using a slightly different syntax to define the child node of the window object.
It is important to know that these functions are considered named function since they are assigned to variables and can be called later in your code. If you do not assign a variable name to a function then the function is considered anonymous. As in the following example.var x = 0;
x = addOne(x);
// x = 1
x = addTwo(x);
// x = 3
x = addThree(x);
// x = 6
x = addFour(x);
// x = 10
You can also add functions as members of an object.var bird = {
chirp: function() {
alert("chirp!");
}
};
Now you can call on bird.chirp.
Another way to use functions is with self-executing functions. These are extremely useful and widely misunderstood. Check out the following example.(function() {
var x = "Hello!";
alert(x);
})();
In this example the function will execute automatically and "Hello!" will be alerted to the user. Since this function is encapsulated the variable x will not be accessible from outside. If you take a look at the source code for jQuery you will notice that the developers use this often. In doing so only the functions they assign to the window object are accessible outside of their code. Which keeps the document tidy.
-
An Introduction to JavaScript Functions
1 Comment Posted on September 29th, 2009
1 Comment
Leave a Comment
-
You
Sep 7, 2010
function counterMaker() {
var count = 0;
function add() {
count++;
return count;
}
return add;
}
var counter = counterMaker();
counter(); // returns 1
counter(); // returns 2
counter(); // returns 3 ...