Monday, February 7, 2011

What you need to know about JavaScript functions

As in any other language, functions are one of the building blocks of JavaScript. You can define functions and call them in different ways. In this article we'll see some basic but important things you need to know about JavaScript functions. 

Function declaration

The basic syntax for creating function declaration is like this. declarations loads to execution context before any code is executed. Below I'll show you function declaration example and 5 ways you can call the function.


Function expression

Functions can be created like expressions as well. Function expression gets load only when interpreter gets to the line of code. Also you can give a name to a function in a function expression they are called named function expression. If you do not give a name to a function expression it'll be called anonymous function expression.

The difference between function expression and declaration is how browser loads them to execution context. With functions comes a important concept called hoisting. Usually in JavaScript variable declarations are hoisted on top of a function. Read this for more info on hoisting

function themselves are objects of type Function. It has methods like apply, call etc.. Every functions by default accepts arguments object. You can find all arguments passed from the caller from argument object. Closures are related with functions. Read this article written by me about closures. JavaScript has predefined functions such as eval, isNaN, parseInt etc. If no return value is defined, functions will return undefined.

You can pass different parameters to functions. If you pass primitive type (primitive types in JavaScript) they get passed by value. But if you pass object (such as Array) the change will be reflected outside the function. That is you're passing an reference to an object by value. There is no pass by reference in JavaScript. 


Constructor functions vs Factory functions
Constructor function uses the new keyword to create a new object, set this within the function of that object and return it.





Factory function also uses to create new objects but it does not use new keyword. In fact factory creates the object for you and returns it. You can return different types of objects from a factory. 



With factories you get better encapsulation and data hiding. 

When you create an object from constructor function the prototype will be included in that object. When you create a n object through a factory since it just returns an object, the prototype won't be available.

Some Useful Stuff

Exclamation mark in front of a function (SO1 , SO2)


Resources

0 comments:

Post a Comment

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook