Javascript Guide - Functions
You can now also navigate the guide through the table of contents.
Now that we know how to create behavioral code, it's time we get lazy. In this post, we're going to talk about yet another key feature of most programing languages - Functions
When we write code, we will often find ourselves writing the same code over and over again. At it's core, a function is a way for us to name a specific piece of code, calling it over and over again.
In fact, we already used functions before - the console.log is a function, and so are pop and shift.
From here on, we are going to start diving deeper into the language, and with this in mind, things are going to start getting complicated. There is no simple way to explain some of these things, and some will require some trial and error. But, with great knowledge come great power, and it is that power that makes JS such a powerful language.
There are 3 main ways that we can define a function: Function declaration, functions as variables, as lambdas.
Function declarations
This is the easiest way for creating a function, and it consists of 4 parts:
- The function keyword specifying we are declaring a function.
- A Function Name a way for us to identify the function.
- A list of variables that the function expects to receive.
- A code block the code we want the function to execute.
Once we declare our function, we can call it, using it's name, passing it variables withing ( ).
And it looks like this:
function log(a){
console.log(a);
}
log('a');//a
log(123);//123
log([1,2,3]);//[1,2,3]
As I said before, functions are way for us to get lazy. Using this function, we can simply do log('a'). But we can also do something more complex:
function logArray(arr){
for (var i =0, l=arr.length; i<l; i++){
console.log(arr[i]);
}
}
logArray(['a','b','c']);
//a
//b
//c
Function Variables
As I mentioned earlier in this series, everything in JS is an Object. That includes functions. What this means is that we can use functions as variables. This is only one step further from our last method:
var log = function(a){
console.log(a);
}
log('bla');//bla
All we really did here was change the way we identify the function. The reason this is useful is when we want to put functions within our Literal Objects:
var obj = {
'myFunc' : function(a){
console.log('i printed this:',a);
}
}
obj.myFunc('abc');//abc
We are already on our path to do some very advanced programing, but we are going to dive a little bit deeper:
Lambda - Anonymous Functions
Lambda is one of the most important aspects of javascript. It is a way in which we can create functions without naming them, passing them as variables.
lambdas are anonymous - by which i mean they have no identifier. In fact, we already created a lambda on the previous example - we simply assigned it to a variable. The next step will be to drop the variable.
It is quite hard to give good examples for lambdas with our current level of knowledge, but it is going to play a major role when we start interacting with our webpages. For now, let's examine the next function:
// a normal function:
function runLambda(func){
console.log('im running this function!');
func();
}
runLambda(function(){
console.log('ran as a lambda!');
});//ran as a lambda
OK - so this might have been a bit confusing. What we did is to create a normal function - runLambda, that receives a function as a parameter, and executes it. The tricky part was that instead of passing it a declared function, we passed it a function declaration, with no name. But since in JS, everything is an object, runLmbda has no problem handling it.
It is OK if you didn't quite get it, but you will see that this will become a second nature for you after a while.
Return
The return keyword is a very special treat - it has 2 main duties:
-
It will stop the current function executing.
function useReturn(a){ if (a===1) return; console.log(a); } useReturn(1); useReturn(2);//2run code -
It allows us to return a value from the function:
function addNumbers(a,b){ return (a+b); } console.log(addNumbers(1,2));//3run code
As you can see, this little feature allows us to create functions that perform operations to create new values. As simple as it seems, it is actually extremely powerful.
Arguments
This is a very important feature of javascript - although it is quite poorly designed. Every function has a special variable in it called arguments. This variable is an array-like object that contains the complete variable stack that was passed to the the current function.
Why is this useful? because it allows us to create functions that receive an arbitrary number of variables. Lets look at the example:
function logArgs(){
for (var i=0, l=arguments.length;i<l;i++){
console.log(arguments[i]);
}
}
logArgs(1,'abc',[1,2],{'a':'b'});
//1
//abc
//[1,2]
//Object(a='a')
Again - it is OK if you don't quite grasp this yet, but it is nice to know about it.
Next Post - Scope Resolution