Functions in JavaScript

Everything in JavaScript is an Object. As we discussed in the previous post, JavaScript even treats the primitive data types as objects to provide additional functionality. Click here to see the example.

Every programming language has functions, and a function is a reusable set of instructions. Apart from this, functions create their own scope. So everything created inside the function will not be accessible from outside.

There are two ways we can create functions in JavaScript,

Function Definition

This is also called function declaration or function statement. Example:

function foo () {
  return “foo”;
}
Function Expression

An expression in any programming language is a way to assign a value to any variable. This is different from a statement, which does not assigns a value. For example, in the above code, return num * num; is a statement, while following is an example of expression:

var a = b + c;

In JavaScript, functions are values, which means functions can be assigned to any variable. So we can write,

var foo = function () {
  return “foo”;
}

// we can also do the following,
var bar = foo;

foo ();    // returns "foo"
bar ();    // returns "foo"

Invoking a function

Invoking a function is simple, if we write the function name followed by a set of parenthesis, we can invoke the function. Invoking a function is also referred to as calling a function. See above code example.

Parameters & Arguments

Every function can accept n number of arguments. While creating a function (in either way) we specify the parameters we have to pass to the function.

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

Note: In the above function, there is an arithmetic operation, but as we are not assigning it to any variable, it is still a statement, not an expression.

Every JavaScript function returns something, if it is not mention, it will return an undefined value.

Parameters to the functions are written in the comma-separated list. While invoking the function, we pass the values for the parameters mentioned, and they are called arguments passed to the function.

arguments

It is a special object in JavaScript which is implicitly created as a local variable during the function execution. This object is used to refer all the arguments passed to the function using index (like an array).

Even though arguments is not an array, it gives indexed access to the arguments passed to the function.

In addition, it also has the length property, which is available to the arrays. Apart from indexed access, and length property, arguments cannot call access/execute other array methods. However, it is possible to call the array methods using apply.

var newArr = [].slice.apply (arguments);

Read more about arguments here.

Hoisting & Function

Unlike variable declarations, functions when created using function expression, they are not hoisted. For example,

// this works

foo ();
function foo () {
  console.log (‘foo’);
}
// prints foo


// this doesn't

bar ();
var bar = function () {
  console.log (‘foo’);
}
// Uncaught TypeError: bar is not a function.

console.log (foobar);
var foobar = 10;
console.log (foobar);

// prints undefined then 10;

Read here why function expressions are not hoisted.

Read about JavaScript code execution and more on hoisting here.

Anonymous Function

Until now, all examples of the functions had a name and we were able to invoke them using the pair of parenthesis. When we do not provide a name for the function, it is called an anonymous function. When an anonymous function is created, it is not possible to refer to it, hence it is not reusable.

Why do we need or use anonymous function?

In general, anonymous functions are created in the following few scenario,

  • One of the major use case of the using an anonymous functions is to create an immediately invoked function expression (IIFE) [explained in the section below].
  • As an event handler, perhaps when the functionality is not reusable. For example, hide a div element on click of close icon.
  • An anonymous function is implicitly created when using bind. Read more about this.
  • With setTimeout, to move a particular execution to the ending of the call stack.

Examples

// event handler, function with no name.

var el = document.getElementById ('close-icon');
el.addEventListener ('click', function (e) {
  // write functionality here
});

// bind
function foo () { };
el.addEventListener ('click', foo.bind (this));

// setTimeout
console.log (1);
setTimeout (function () {
  console.log (2);
}, 0);
console.log (3);

// output
1
3
2

IIFE (Immediately Invoked Function Expression)

As the name suggests, an immediately invoked function expression is a function which gets invoked/executed as soon as the JS engine reaches to the end of the function. To achieve this, we need to function inside a pair of parenthesis, then invoke it.

Example

// normal function
function () {}

// wrap within ()
(function () {})

// execute it.
(function () {}) ();

An IIFE is commonly used,

  • While creating a module, read here.
  • When we need to initialise something as soon as the code is loaded.