Variable & Function Declarations vs Expressions
Variable Declarations
You can declare a variable with the var keyword followed by a variable name of your choosing.
var aVariable; // A Variable Declaration
Variable Expressions
You can assign some data to the variable with equals sign= , the code right of the = is called the Variable Expression Assignment.
var aVariable = 'a string'; // A String Expression Assignment
var aNumber = 123; // A Number Expression Assignment
var anObject = {key:'value'}; // An Object Expression Assignment
var anObject = [12,3,'a string']; // An Array Expression Assignment
Function Declarations
Just as you declare a variable with var you can declare a function with function. Declared functions must be named they cannot be anonymous.
// Named Function
function fnDeclaration (){
return 'I am a Function Declaration';
};
Function Expressions
A function that is part of a larger syntax construct is called a function expression, typically you achieve this by assigning the function to a variable or an objects key/value pair.
// Anonymous function expression
var fnExpression = function(){
return 'I am an Anonymous Function Expression';
};
// Anonymous function expression assigned to a key/value pair.
var obj = {};
obj.fnExpression = function(){
return 'I am a different Anonymous Function Expression';
};
// Named function expression (Beginners should avoid this last one)
var foo = function fnExpressionToo (){
return 'I am a Named Function Expression';
};
Differences between Function Declarations and Expressions
Named and Anonymous Functions
Only function expressions can be anonymous, that is, written without a name after the function keyword. In the examples above anonymous functions are accessed by their variable assignment.
Hoisting
Function declarations are hoisted so invoking a function declaration before it is defined works just fine. You will rarely want to invoke a function before it was defined and if you write well structured code you may be forgiven for not even noticing the hoisting behaviour of JavaScript.
Hoisting is a topic all of its own and past the scope of this article, but you can read all about it in Variable & Function Hoisting.
An error has occured with your submition. Sorry there is no further details, if the problem persists please use the contact form to inform us.