Function constructor vs Function declaration vs Function expression

December 2, 2007 § Leave a comment

This is 1 topic that I usually take for granted but never really quite “gets” it.

A function can be defined with Function Constructor assigned to variable. Example:

var multiply = new Function(“x”, “y”, “return x * y;”);

Function Declaration is typically used to define a function. Example:

function multiply(x, y) {

return x * y;

}

Function Expression, without name, can also be used to define a function to variable. Example:

var multiply = function(x, y) {

return x * y;

}

Function Expression can also be assigned a name. Example:

var multiply = function func_name(x, y) {

return x * y;

}

What exactly the differences between all those? Not much. But there are quite a number of trivia that I need to remember from now on.

Function Constructor (i.e. new Function(a, b, c)) is parsed EVERY TIME javascript is evaluated. Bad! Real bad! In contrast, Function Declaration and Function Expression are only parsed 1 time.

Obviously function name defined by Function Expression/Function Declaration cannot be changed, while the variable, to which the function is assigned to, can be manipulated/reassigned.

Function name defined by Function Expression can be used only inside the function body. Meanwhile, Function Declaration CREATES a variable with the same name as the function name. Thus, unlike Function Expression, Function Declaration can be accessed by its name in the scope they were defined in. Example:

var y = function x() {};

alert(x); // throws an error because the name “x” is not accessible outside the function

function x() {}

alert(x); // outputs x serialized into a string. It works.

Function Declaration automatically becomes Function Expression when it is defined inside conditional loop.

Trivia:

  • Every function contains Arguments array-like object.

Reference:

Mozilla Development Center – Functions

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Function constructor vs Function declaration vs Function expression at RAPD.

meta

%d bloggers like this: