JavaScript : Functions are Objects
JavaScript is easy to learn at first sight since everything seems simple enough but to master the language, it will take a lot of effort and time. People coming from a class based language like Java or PHP, JavaScript will be a bit confusing as it doesn’t follow a class based structure and follows a prototype based inheritance.
One of the main concept you should understand to get better in JavaScript is functions. Functions are a fundamental feature in any programming languages and in JavaScript, it plays a prominent role.
Functions help us to write less code and stops us from repeating our code.
In JavaScript functions have an extra job to perform, creating objects. As I mentioned earlier JavaScript doesn’t follow a class based inheritance but still we need to create objects so we can group our related logic together.
You may wonder how can we create an object out of a function. Functions are used to wrap repeating code right?. But in JS , we can use it to create objects using the new keyword. To do this we need something called function constructors.
Functions are a type of object with two special properties, name and code. A function can be named or anonymous. If it’s named then the name will be stored in name property and the code we want to execute will be stored in code. When we try to invoke a function , JavaScript will try to execute the code segment in the code property.
As we can see in the above image, our myFunction in the window object have a property called name which have the property name as “myFunction”
This function will be remain as a normal function until it is called with the new keyword. When we call the function with new keyword, the function’s prototype.constructor method is called which can instantiate new objects from this function.
Since functions are a type of objects, we are able to attach properties to the functions. As you can see in the above image, there are several properties and methods in the “myFunction” function.
We can use the function’s prototype property to store our methods which are common to all objects created using this function. This will help to save all the methods in one place and helps us to reduce the memory footprint of our objects since our methods are stored in the prototype not in the individual objects.
Having functions as type of object helps us to pass our functions into another functions as arguments and open new possibility of writing good programs. I hope you got little more understanding of functions in JavaScript. If you like the article or have any suggestions on improving my article, please reply to this article or contact me.