Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Functions in JavaScript

4.00/5 (1 vote)
7 Nov 2013CPOL3 min read 4.3K  
Functions in JavaScript

Functions

 

Functions are not a tool in JavaScript, they are "The Tool" in JavaScript. For all the functionality that other object oriented languages have that JavaScript does not, functions can implement, simulate and to some extent, bend the rules to provide the equivalent to that of traditional languages.

What Can I do with a Function?

The better question is what can't you do with them.
Functions can be:

  • Passed as arguments
  • Returned as values
  • Assigned to a variable
  • Stored in a data structure
  • Nested (Closures more on this later)
  • Anonymous (Lambda Expressions)

Additional just about all functions in JavaScript can be overwritten (including the built in ones) so if you come from a language with Method Overriding, you can think of all functions in JavaScript as being virtual. Thinking about that for a second... you have the power to change just about anything...

Uncle Ben likes functions and so should you.
Uncle Ben

As Uncle Ben once said with great power comes great responsibility. Which is exactly why using things like closures to scope functions is important as I will show you a bit about later.

Function Declarations 

So we have three ways to declare functions, the first of which is called the functional statement. The key thing to remember about the functional statement is that by default, it is declared in the global scope (which is usually the parent document window in most cases).

JavaScript
 //function declaration ||the function statement
function add(a,b){
	return a + b;
}
//The function expression (function operator)
//Function Literal
var add = function (a, b) {
    return a + b;
};
//The Function constructor
var add = new function(a, b){
	return a+b;
}  //function declaration ||the function statement
function add(a,b){
	return a + b;
}
//The function expression (function operator)
//Function Literal
var add = function (a, b) {
    return a + b;
};
//The Function constructor
var add = new function(a, b){
	return a+b;
} 

Check out this link

Just What the Heck is a Closure? 

A closure is any function which closes over the environment in which it was defined. This means that it can access variables not in its parameter list. Closures are the bread and butter of JavaScript and are the means by which JavaScript can emulate other languages object oriented nature. 

//http://stackoverflow.com/questions/111102/how-do-javascript-closures-work 

JavaScript
//foo "encloses bar" hense the name "closure"
//
function foo(x) {
  var tmp = 3;
  function bar(y) {
    alert(x + y + (++tmp));
  }
  bar(10);
}
foo(2);

Check out this link to play with the example in jsFiddle 

 

 

Anonymous Methods 

Anonymous

Anonymous, you mean like a Jon Doe or like that Hacker group? Or like the horse with no name? 

 

Those masks really freak me out.

A horse with no name....? 

 

 

 

 

 

 

 

 

 Well, if I had to pick, I'd say they are somewhat closer to the horse.... maybe. 

 

 

 

Anonymous methods are methods that do not have a method named attached to them. In particular to JavaScript, they are often used as a means to manage the scope of an object, module, or namespace as such. In this quick jQuery example, we pass the button an anonymous function that declares a variable. The function only gets called when the button is clicked and only lives as long as the lifetime of the button click itself. 

 

 

JavaScript
 //the click method takes a callback that gets called when the button is clicked   
JavaScript
$("#exeBtn").click(function(){
    var poorVariable = "Alas woe as me for I only live in the scope of this click callback";
    alert(poorVariable);
});

/*
When you look at your debugger you will see something like
Uncaught ReferenceError: poorVariable is not defined 
when we make our console.info(poorVariable) call 
because the poorVariable is no longer with us at this point :( poor poor poorVariable
*/
console.info(poorVariable);

Check out this link to play with the example in jsFiddle 

Also often used to act as events within another function.

An example you'd commonly see out in the wild would be the jQuey Ajax Request function.

/*in this case it won't work because of the cross domain security policy enforced. So with that you will see the failure callback which produces the it didn't work alert box. If you look at your debugging console you will see something like 

JavaScript
/*XMLHttpRequest cannot load http://musicm122.blogspot.com/. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin. */
*/

//http://api.jquery.com/jQuery.ajax/
//the done and fail functions both take a function as an
//argument and execute in different circumstances
var myRequest = $.ajax({
    url: "http://musicm122.blogspot.com",
    context: document.body
}).done(function (data) {
    $("#contentDumper").html(data);
    alert("done");
}).fail(function(){
    alert("it didn't work :(");
});

//the click method takes a callback that gets called when the button is clicked
$("#exeBtn").click(function(){
    myRequest();
});

 Check out this link to play with the example in jsFiddle. 

*Note: I use jQuery with both because jQuery is pretty close to synonymous with JavaScript on many a website and felt it to be more realistic and relevant to the discussion.

Well that about wraps up my brain dump about functions. This post is (for the most part) an adaptation of my talk on JavaScript fundamentals. If this stuff is making your brain itch, then you should look out for my next JavaScript presentation.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)