Functions as Data in JavaScript
Functions in JavaScript are objects and can therefore be used as data. Here are a few examples:
1. Assigning a function to a variable:
|
|
In this example, we assign a function to the variable greet
. We can then invoke the function using the variable name.
2. Storing functions in an array:
|
|
Here, we have an array functionArray
containing two functions. We can access and execute these functions using their index in the array.
3. Using functions as object properties (methods):
|
|
In this example, we’re using a function as a method of an object. We can then invoke this method using dot notation.
4. Passing functions as arguments:
|
|
In this example, we pass a function as an argument to another function and execute it within that function.
5. Returning a function from a function:
|
|
In this example, a function getGreeter
is returning another function. We can then store the returned function in a variable and invoke it later.
These examples illustrate that functions in JavaScript can be used as data, which can be assigned to variables, stored in data structures, passed as arguments to other functions, and returned as values from other functions. This feature provides a lot of flexibility in writing JavaScript code.