Are functions objects in javascript?
Last Updated : 19 Nov, 2024
Improve
Yes, Functions are considered first-class objects, which means they have the same capabilities as other objects. The following are examples that demonstrates functions behaving as objects:
Can be assigned to variable
// Assign a function to a variable
const x = function() {
return `GfG!`;
};
// Call the function with the variable name
console.log(x()); // Outputs: GfG!
Output
GfG!
Can be passed to other functions
function fun1() {
return `GfG`;
};
function fun2(fun) {
console.log(fun());
}
fun2(fun1);
Output
GfG
Can be returned from functions
function getFun(x) {
return function(y) {
return x * y;
};
}
const res = getFun(2);
console.log(res(5));
Output
10
Can have properties and methods
// Define a function that adds two numbers
function add(a, b) {
return a + b;
}
// Add a custom property to the function
add.description = "Adds two numbers.";
console.log(add(3, 4));
console.log(add.description);
Output
7 Adds two numbers.