Function object in JavaScript

Function object provides the prototype for all functions in JavaScript. When function does not return anything, undefined is returned by default. Functions are also objects. All function objects have one property – [[Call]].

There are 2 types of functions.

  1. Anonymous
  2. Named functions

Main difference between anonymous functions and named functions is that named functions are hoisted. It means that we can call named functions before their declaration in a source file. In general, hoisting means moving all declarations to the top of source code.

Anonymous functions

var anonymousFunc = function(a,b){
return a+b

console.log(“Addition using anonymous function -> ” + anonymousFunc(11,22))

We can use below syntax to define above function using “Function” constructor.
var anonymousFunc = new Function ( “a” ,”b”, “return a + b ;” );

Named functions

function add(a,b){
return a+b

console.log(“Addition using named function -> ” + add(22,33))

Passing arguments to the functions

There are 2 ways in which we can pass arguments to the function.

  1. Unnamed arguments
  2. Named arguments

Each function takes variable number of arguments. So methods do not have a signatures in JavaScript. We can pass as many arguments to the function as we want. In JavaScript, you do not need to pass values for all parameters. For example, we can call the
add method with just single parameter.

To find out how many arguments are required by the specific function, you can check it’s arity by accessing “length” property of the function.

You can access all arguments passed to the function using special array “arguments”.

arguments[0] is the first argument passed to the function. arguments[1] is the second argument passed to the function and so on.

Multiple functions with same name

You can have multiple functions with same name but only last one in the source code is used.

You may also like...