Little Known Facts on Functions In Javascript

Little Known Facts on Functions In Javascript

Functions In Javascript: JavaScript embraces a wide range of functional programming principles alongside its object-based programming foundation.

Let's explore the different ways to define Functions in JavaScript and their Practical uses.

Function declaration

Javascript Functions

This is the commonly used syntax for defining functions.

Hoisting & Scope: Function declarations are hoisted to the top by default and the scope of this function is either global or scoped to the function inside which this is declared.

Function declarations are loaded before any code is executed.

For larger applications, using too many function declarations has a higher chance of polluting the global scope and affecting the initial load time.

Function expression

Function Expression

Function expressions are a much better way to define functions.

Hoisting & Scope: Function expressions are not hoisted similar to function declarations. Its scope is based on the variable to which it's assigned.

Function expressions can be used to,

  • Send functions as arguments to other functions

  • Create closures

Function expression will not pollute global scope by keeping them private.

IIFE (Immediately Invoked Function Expression)

Also known as the Self-executed Anonymous function is a form of function expression that is run only once at the time of definition.

Javascript Function

It helps to create a private scope for variables defined inside functions without polluting global scope.

It can be used for initialization tasks for the first time.

Arrow functions

Starting from ES6 release, Arrow functions are introduced, providing a simpler way to define function expressions.

Arrow Functions

Arrow functions are not hoisted.

The main difference between other function definitions and arrow functions is the binding on 'this'.

It doesn't have any binding to 'this'. Other function definitions and expressions have 'this' binding to the associated object or with the global window object.

So, this is not suited to define object methods.

Let's do a comparison of different types of functions in JavaScript.

Higher-order functions

Higher-order functions receive other functions as arguments, return functions or do both.

Javascript Functions

In this example, forEach is a higher-order function that accepts a function as an argument. map, filter, reduce, and sort are some frequently used higher-order functions.


References