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.

Notes<br />

The arguments.length property was deprecated in <strong>JavaScript</strong> 1.4, but the number of<br />

arguments sent to a function can be accessed from the length property of the function<br />

object. Moving forward, you can get the length value by leveraging the callee property<br />

to first gain reference to the function being invoked (i.e. arguments.callee.length).<br />

Redefining function parameters<br />

A function’s parameters can be redefined inside the function either directly, or by using<br />

the arguments array. Take a look at this code:<br />

Sample: sample87.html<br />

<br />

var foo = false;<br />

var bar = false;<br />

var myFunction = function (foo, bar) {<br />

arguments[0] = true;<br />

bar = true;<br />

console.log(arguments[0], bar); // Logs true true.<br />

}<br />

myFunction();<br />

<br />

Notice that I can redefine the value of the bar parameter using the arguments index or<br />

by directly reassigning a new value to the parameter.<br />

Return a function before it is done (i.e. cancel function execution)<br />

Functions can be cancelled at any time during invocation by using the return keyword<br />

with or without a value. In the following sample, we are canceling the add function if the<br />

parameters are undefined or not a number.<br />

Sample: sample88.html<br />

<br />

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

// If the parameters are not numbers, return error.<br />

if (typeof x !== 'number' || typeof y !== 'number') { return 'pass in<br />

numbers'; }<br />

return x + y;<br />

96

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

Saved successfully!

Ooh no, something went wrong!