JavaScript — Functions

Himesh Vats
3 min readJun 22, 2019

…You will need to know this…at least

1. Function Definition and Invocation

JS functions can be declared in multiple ways :

Function Declaration

Declared functions are not executed immediately. They are “saved for later use”, and will be executed later, when they are invoked (called upon)

Function Expression

A Function Expressions defines a named or anonymous function can be stored to a variable.

Arrow Functions

An Arrow Function Expression is a shorter syntax for writing function expressions. Arrow functions do not create their own this value.

Function Constructor

Functions can also be defined with a built-in JavaScript function constructor called Function().

Self-Invoking Function

A self-invoking expression is invoked (started) automatically, without being called. Function expressions will execute automatically if the expression is followed by ().

Function Invocations

Invocation of a function is executing the code that makes the body of a function, or simply calling the function.

A simple example of function invocation :

A more advance example is the IIFE :

The key to understanding this keyword is having a clear view over function invocation and how it impacts the context.

In JavaScript this is the current execution context of a function.

JavaScript has 4 function invocation types:

  • Invoking a function as a Function: alert('Hello World!')
  • Invoking a function as a Method : console.log('Hello World!')
  • Invoking a function with a Function Constructor : new RegExp('\\d')
  • Indirect invocation: alert.call(undefined, 'Hello World!')

…as a Function

this is the global object in a function invocation.

But not in Strict Mode

…as a Method

this is the object that owns the method in a method invocation

Constructor invocation

Or Using Class Syntax

this is the newly created object in a constructor invocation

Indirect Invocation

this is the first argument of .call() or .apply() in an indirect invocation

& in Bound Function

this is the first argument of .bind() when invoking a bound function

…also in Arrow Function

this is the enclosing context where the arrow function is defined

You can read more about the Functions and their Invocations here : https://dmitripavlutin.com/gentle-explanation-of-this-in-javascript/

You can follow me on Medium by scanning this 👇

--

--