JavaScript Functions

Swathi Bhat
3 min readSep 18, 2021

JavaScript is mostly a functional language. It uses functions to implement most of the programming scenarios like asynchronous tasks, Object-Oriented-Programming paradigm etc. In JavaScript, functions are treated equivalent to objects — they are sent as arguments to other functions, and returned from other functions among other ways.

Functions can be declared as traditional functions, expressions, anonymous functions or or using the arrow operator depending on the requirement.

The traditional functions are defined:

Traditional function

These functions are taken as methods and not expressions. They are stored as a function and not in a variable. They are hoisted to the beginning of the scope and hence can be used before they are defined or declared.

Another variant is the anonymous function, which has no function-name attached to it.

These functions are mostly used where the function is immediately called, or when sending it to another function as argument (for example, a callback function). But, the anonymous functions are useless unless used immediately, since they have no way of being identified.

Another type of function is the function expression:

These functions are taken as expressions rather than functions. They are assigned to a variable and stored in a variable. So, they are not hoisted to the beginning of the scope. Hence they can only be used or called once they are declared or defined. These functions are used when the functions need to be treated as variables or expressions. They are also useful when assigning functions to object methods. These are assigned a “name” attribute.

The most recent addition to functions is the arrow function or an inline function. It is implement in the ES6 JavaScript version:

These functions are treated as inline functions. They are expanded where they are defined. Although the arrow functions have a shorter syntax, they cannot be used as methods of an object and apply, bind, call cannot be used on them. This is because, they have no context. They do not have the ‘this’ binding. They do not have “arguments” that contains all the arguments passed. They do not “yield” and do not “new.target”. All these advantages of the regular functions are traded in for lesser and simpler code.

One of the main features of the arrow functions is the implicit return. The function body with a single statement implies a return:

This implies:

This is especially useful when using methods like map and filter, where functional-style code is used:

In short, each type or style of function has its own positive and negative points. The most optimal style would be the one most useful at that situation.

--

--

Swathi Bhat

A software developer based out of Bangalore, who loves to talk about JavaScript!