Functions are Objects in JavaScript

Whattttt???

Confused man

Yes, You read that correctly.

Let's deep dive into this topic.

Before we get into a serious drill, Let's quickly revise objects and functions in JavaScript.

Object:

Objects in JavaScript are nothing but a non-primitive type data structure. We can define an object using curly brackets and put key-value pairs separated by a comma in it.

const user = {
   name:"Hemendra",
   nickname:"Hemu",
   email:"hi@aamchora.space",
}

user.city = "Bhilwara" // add new value in existing object

user.city = "Jaipur" // update new value in existing object

console.log(user.name);
/*
output

Hemendra

*/
console.log(user);

/*
output

{
   name:"Hemendra",
   nickname:"Hemu",
   email:"hi@aamchora.space",
   city:"Jaipur"
}
*/

Read more about objects in depth.

Function

Unlike other programming languages, JavaScript has implemented the functions very differently.

Let's have a look

Definition:

A function is a block of organized code that performs a specific task.

Advantages of functions

  • Functions make your program easier to read, understand, and debug.
  • Functions can make a program smaller by eliminating repetitive code.

Now you would be wondering, What's the difference then?

What is different

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. Every JavaScript function is actually a Function object.

Now way gif

Let's see how we define functions in JavaScript first

function sum(a,b){
 return a+b;
}

const res = sum(2,4);

console.log(res); // outputs -> 6

Above we have created a function named sum which adds two numbers.

But as I said earlier, is the sum function created above also an object? can we add properties and values to the sum function as we did in the user object above?

let's see this in action


function sum(a,b){
 return a+b;
}

sum.help = "use this function to add two numbers";
// like an object we have added help key and it's value to the above function.
// will work as before
const res = sum(3,6);
console.log(res) // outputs --> 9

// but now 

console.log(sum.help) 
// outputs --> use this function to add two numbers

Let's verify if the sum function is an instance of an object or not


function sum(a,b){
 return a+b;
}

console.log(sum instanceof Function); // true
console.log(sum instanceof Object); // true

let name = "Hemendra"
console.log(name instanceof Object); // false

And Voila, It proves that the functions are objects in JavaScript.

I was right gif


follow me for more such blog posts.

Let me know if this blog was helpful.

Did you find this article valuable?

Support aamchora by becoming a sponsor. Any amount is appreciated!