Functions as data

In JavaScript, functions can be assigned to variables, and variables are data. You will shortly see that this is a powerful concept. Let's see the following example:

var say = console.log;
say("I can also say things");

In the preceding example, we assigned the familiar console.log() function to the say variable. Any function can be assigned to a variable as shown in the preceding example. Adding parentheses to the variable will invoke it. Moreover, you can pass functions in other functions as parameters. Study the following example carefully and type it in JS Bin:

var validateDataForAge = function(data) {
  person = data(); console.log(person); if (person.age <1 || person.age > 99){ return true; }else{ return false; } }; var errorHandlerForAge ...

Get JavaScript: Moving to ES2015 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.