Functions as data

A function in JavaScript is treated like data. How? We can assign a function to a variable and store a function in a data structure.

Assign to variable

One way to define a function is to use the function declaration as demonstrated in the next example:

function greet(name) { return `Hello, ${name}`; } console.log(greet("Sam"));

To assign a function to a variable, all we have to do is assign the function declaration to a variable, like so:

const hi = function greet(name) { return `Hello, ${name}`; }; console.log(hi("Sam"));

A second way to assign a function to a variable is to declare an anonymous function and assign the function expression to a variable.

const greet = function (name) { return `Hello, ${name}`; }; console.log(greet("Alex"));

A third way is to declare the function as an arrow function expression and assign the function expression to a variable.

const greet = (name) => `Hello, ${name}`; console.log(greet("Ashlie"));

Treating functions like data also allows us to rename functions without changing their declarations. Have you ever encountered a function name that is rather long and unwieldy to type? Like myAwesomeRoutine()? You do not need to change the function name wherever it occurs in a bunch of source files. Simply assign the function to a shorter variable name. Here is an example.

const politeSalutation = (name) => `Hello, ${name}`; const hi = politeSalutation; console.log(politeSalutation("Sammy")); console.log(hi("Sam"));

Store in data structure

Primitive data like strings and numbers can be stored in data structures such as arrays, sets, maps, and objects. We learnt from the section Assign to variable that JavaScript treats functions as if they were data. We would expect to be able to store functions in data structures in the same way as we can store strings and numbers in data structures. Indeed we can, as shown in the next example.

// Store functions inside an array. const bird = () => "tweet"; const cat = () => "meow"; const dog = () => "woof"; for (const pet of [bird, cat, dog]) { console.log(pet()); }

We can take this concept further by embedding functions inside objects. That is essentially how JavaScript supports the concept of a class. Here is an example on how to assign a function as a value of an object key.

// Store functions inside an object. const pet = { name: "Tabby Whiskers", purr: () => console.log("Purrrr"), like: (food) => food === "fish", }; console.log(pet.name); pet.purr(); console.log(`Likes fish? ${pet.like("fish")}`); console.log(`Likes lemon? ${pet.like("lemon")}`);

Exercises

Exercise 1. In the following function declaration, the function name is rather long. Change the function name to a shorter, descriptive name without changing the function declaration.

function meaningOfLife() { return "Try and be nice to people"; }

Exercise 2. A principle of readable code is: Choose a "good" function/variable name. How do we choose a "good" name for our function or variable? See Chapter 11: The Power of Variable Names of the following book:

  • Steve McConnell. Code Complete. 2nd edition, Microsoft Press, 2004.

Exercise 3. Choosing a "good" function/variable name is part of what makes good programming style. The following texts offer some guidelines worth reading:

  • Brian W. Kernighan and P. J. Plauger. The Elements of Programming Style. 2nd edition, McGraw-Hill, 1978.
  • Henry F. Ledgard. Programming Proverbs: Principles of Good Programming with Numerous Examples to Improve Programming Style and Proficiency. Hayden Book Company, 1975.

Exercise 4. Modify the script noise.js to store the given functions inside a set. Repeat the exercise, but store the functions inside a map.

Exercise 5. Tabby does not like lemons. Modify the script cat.js to declare a function that returns whether Tabby dislikes a particular food. The function declaration should be the value of a key in the object pet.

Exercise 6. Modify the script cat.js by rewriting the object pet as a class.

Exercise 7. Implement an object math each of whose keys references a function to perform a mathematical operation. Use the following template to help you get started.

const math = { max: (a, b) => /* Code for maximum of 2 numbers */, min: (a, b) => /* Code for minimum of 2 numbers */, square: (x) => /* Code for the square of a number */, }; console.log(math.max(3, 2)); // => 3 console.log(math.min(3, 2)); // => 2 console.log(math.square(4)); // => 16

results matching ""

    No results matching ""