Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

4. Function() > Defining a Function (Statement, Expression, or Constructor)

Defining a Function (Statement, Expression, or Constructor)

A function can be defined in three different ways: a function constructor, a function statement, or a function expression. Below, I demonstrate each variation.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

/* function constructor: the last parameter is the function logic,
   everything before it is a parameter */
var addConstructor = new Function('x', 'y', 'return x + y');

// function statement
function addStatement(x, y) {
   return x + y;
}

// function expression
var addExpression = function(x, y) {
    return x + y;
};

console.log(addConstructor(2,2), addStatement (2,2), addExpression (2,2)); 
  // logs '4 4 4'

</script></body></html>

Note

Some have said that there is a fourth type of definition for functions, called the “named function expression.” A named function expression is simply a function expression that also contains a name (e.g., var add = function add(x, y) {return x+y}).


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint