Yes, in JavaScript, functions are treated as first-class objects, meaning that they can be assigned to variables, passed as arguments to other functions, returned from functions, and operated on using the same methods as other objects.
Here's an example:
function add(a, b) {
return a + b;
}
const addFunction = add;
console.log(addFunction(3, 4)); // Output: 7
// The add function is assigned to the variable addFunction
// It can be passed as an argument to another function
function multiply(a, b) {
return a * b;
}
const multiplyFunction = multiply;
console.log(multiplyFunction(3, 4)); // Output: 12
// The multiply function is assigned to the variable multiplyFunction
In this example, we define a function called add
that takes two arguments and returns their sum. We then assign this function to the variable addFunction
. This allows us to call addFunction(3, 4)
, which outputs 7
.
Furthermore, we define another function called multiply
and assign it to multiplyFunction
. When we call multiplyFunction(3, 4)
, it outputs 12
.
This demonstrates how functions can be treated as first-class objects in JavaScript. They can be assigned to variables, passed as arguments, and returned from other functions, just like any other object.