06.07.2017 Views

Mastering JavaScript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 2<br />

Functions as data<br />

In <strong>JavaScript</strong>, functions can be assigned to variables, and variables are data. You will<br />

shortly see that this is a powerful concept. Let's see the following example:<br />

var say = console.log;<br />

say("I can also say things");<br />

In the preceding example, we assigned the familiar console.log() function to the<br />

say variable. Any function can be assigned to a variable as shown in the preceding<br />

example. Adding parentheses to the variable will invoke it. Moreover, you can pass<br />

functions in other functions as parameters. Study the following example carefully<br />

and type it in JS Bin:<br />

var validateDataForAge = function(data) {<br />

person = data();<br />

console.log(person);<br />

if (person.age 99){<br />

return true;<br />

}else{<br />

return false;<br />

}<br />

};<br />

var errorHandlerForAge = function(error) {<br />

console.log("Error while processing age");<br />

};<br />

function parseRequest(data,validateData,errorHandler) {<br />

var error = validateData(data);<br />

if (!error) {<br />

console.log("no errors");<br />

} else {<br />

errorHandler();<br />

}<br />

}<br />

var generateDataForScientist = function() {<br />

return {<br />

name: "Albert Einstein",<br />

age : Math.floor(Math.random() * (100 - 1)) + 1,<br />

};<br />

};<br />

[ 49 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!