Over the moon / function syntax


#1

Hey all -
I'm having a hard time figuring out the difference between these two ways of writing a function. Is there one? When would one be more acceptable over the other?
Thanks


function StaffMember(name, discountPercent) {
this.name = name;
this.discountPercent = discountPercent;
};

var StaffMember = function(name, discountPercent){
this.name = name;
this.discountPercent = discountPercent;
};


#2

The first example is a declaration. The entire thing is one self-contained statement. It is an object that gets hoisted to the top of its scope at load time. We refer to these as named functions since they require a name. Function declarations are immutable and cannot be removed from memory or altered during the session.

The second example consists of two parts. A var declaration, which gets hoisted at load time, and an anonymous function expression which does not. In technical terms they are both valid functions and will perform exactly the same way. Hoisting is what sets them apart. A hoisted function can appear anywhere in the source, above or below where it is first called. An expression must appear above where it is first called.

Terms to look up and study...

function declaration

function expression

scope

hoisting

constructor

this

argument

parameter

Extra notes:

Like all variables, the one we use to assign the function expression may be reassigned (given a new value or function expression). This is a convenience in a sense in that we can have a set of expressions that we logically assign to the single variable.

Consider the following ternary expression:

var f = bar === "foo" ? function (bar) { } : function (foo) { };

Here we are assigning one or the other anonymous function to the variable f that depends upon the value of bar. We won't be covering anything this complex so just set this concept on the back burner for now. You may encounter this sort of logic in your studies.


#3

Thanks for the response. I'll make sure to look into these terms.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.