What is actually a "function" in JavaScript?

In JavaScript, the functions are first-class objects.

Now, one would ask, what is a first-class object?

Answer: Just like any other object in JavaScript, functions are also objects. They can have properties and methods associated with them. But they differ from other objects in the sense that they are Function objects.

Focus your attention on this keyword: Function

Function is a constructor to make an instance of a function. Or in other words, a Function constructor is used to make a function object. This means that just like in any other programming language we call the constructor of a class to initiate an instance (object) of that class, similarly, here calling the Function constructor can create functions dynamically.

Just like an object has properties and methods, the functions in JavaScript can also have properties and methods associated with them.

Function properties:

There are various properties of function like arguments, length, name, etc. More details...

Function methods:

There are various methods like call(), apply(), bind(), etc. I will post a different article about these methods in detail later. If you want to check them out now click here.


The syntax of calling the Function constructor:

new Function([arg1 [, arg2 [, ...argN]] ,] functionBody)

arg1, arg2, ...argN: Corresponds to the arguments passed to the function expression. Each must be a string or list of strings.

functionBody: JavaScript statements inside the function body. Must be a string.

Now let's have a look at an example of calling the Function constructor.

// Creates a function that takes an argument of name, and returns the concatenated string containing the argument passed 
const greet = new Function('name', 'return "Hello " + name');

// Call the function
greet('John'); // Hello John

// Calling without argument
greet(); // Hello undefined

// It is equivalent to defining a function expression like this
const greet = function(name) {
    return 'Hello ' + name;

Notice the arguments should be strings. All arguments passed to the Function constructor are treated as the names of the parameters in the function created. Omitting an argument while calling the function can result in an undefined value for that parameter.

If you found this article helpful please share it with others so that they will also get the benefit. Feedbacks are welcome: Twitter | Instagram | LinkedIn

No Comments Yet