Function Declarations vs Expressions

Description

Function declarations are read and available in an execution context before any code is executed.

Function expressions aren't complete until the execution reaches that line of code.

Example


console.log(sum(10,10));
function sum(num1, num2){
   return num1 + num2;
}

The code above has no error, because function declarations are read and added to the execution context first.

Changing the function declaration to an equivalent function expression will cause an error, since the function is part of an initialization statement, not part of a function declaration.


console.log(sum(10,10));
var sum = function(num1, num2){
   return num1 + num2;
};

Example 2

We can assign the correct function expression to the variable myFunction based on condition.


//  w  w  w  .j  av a2s .  co  m
    //this is okay
    var myFunction;
    var condition = true;
    if(condition){
        myFunction = function(){
            console.log("Hi!");
        };
    } else {
        myFunction = function(){
            console.log("Yo!");
        };
    }
    console.log(myFunction.toString());

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions