Functions As First-Class Objects in JS
Functions As First-Class Objects
In JavaScript, functions are considered first-class objects. This means that they can be treated like any other object, assigned to variables, passed as arguments to other functions, and returned as values from functions. Here are some examples:
1. Assigning a function to a variable:
const greet = function(name) { console.log(Hello,$name!); }
2. Passing a function as an argument to another function:
function calculate(operation, num1, num2) { return operation(num1, num2); } const sum = function(a, b) { return a + b; } const difference = function(a, b) { return a - b; } console.log(calculate(sum, 5, 3)); // output: 8 console.log(calculate(difference, 5, 3)); // output: 2
3. Returning a function from another function:
function multiplyBy(factor) { return function(number) { return number * factor; } } const double = multiplyBy(2); const triple = multiplyBy(3); console.log(double(5)); // output: 10 console.log(triple(5)); // output: 15
In this example, the multiplyBy function returns another function that takes a number as an argument and multiplies it by the factor parameter passed to the outer function. The returned function is then assigned to variables double and triple, which can be called later to multiply a number by 2 or 3, respectively.
No Comment! Be the first one.