17.11.2015 Views

JavaScript_Succinctly

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

}<br />

console.log(add(3, 3)); // Logs 6.<br />

console.log(add('2', '2')); // Logs 'pass in numbers'.<br />

<br />

The concept to take away here is that you can cancel a function's execution by using<br />

the return keyword at any point in the execution of the function.<br />

Defining a function (statement, expression, or constructor)<br />

A function can be defined in three different ways: a function constructor, a function<br />

statement, or a function expression. In the following example, I demonstrate each<br />

variation.<br />

Sample: sample89.html<br />

<br />

/* Function constructor: The last parameter is the function logic,<br />

everything before it is a parameter. */<br />

var addConstructor = new Function('x', 'y', 'return x + y');<br />

// Function statement.<br />

function addStatement(x, y) {<br />

return x + y;<br />

}<br />

// Function expression.<br />

var addExpression = function (x, y) {<br />

return x + y;<br />

};<br />

console.log(addConstructor(2, 2), addStatement(2, 2), addExpression(2,<br />

2)); // Logs '4 4 4'.<br />

<br />

Notes<br />

Some have said that there is a fourth type of definition for functions, called the "named<br />

function expression." A named function expression is simply a function expression that<br />

also contains a name (e.g., var add = function add(x, y) {return x+y}).<br />

97

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!