dots Created with Sketch.
Yogesh Chauhan's Blog

Different Types of Functions in JavaScript

in JavaScript on March 9, 2020

The function keyword can be used to define a function inside an expression.


let myFunction = function [function name]([parameter 1 [, parameter 2[, ..., parameter N]]]) { statements};

The name of the function in the syntax above is optional. A function without a name will be called anonymous function.

//anonymous function

var myFunction = function() {
  return "statements"
console.log(myFunction()); //statements

If we include the name then the function will be called named function.

//named function

function hello(name) {
  return `Hello ${name}!`;

console.log(hello('')); //

Function Expression

A JavaScript function can also be defined using an expression.

For example,

function calculateRectangleArea(width, height) {
  return width * height;

console.log(calculateRectangleArea(5, 6)); // 30

Named Function Expression

Whenever we need to refer to the current function inside the function body, we need to create a named function expression. This name is then local only to the function body (scope).

For example,

var foo = function() {} // "foo"

var foo2 = foo // "foo"

var bar = function baz() {} // "baz"

In the example above, The variable the function expression is assigned to will have a name property.

The name doesn’t change if it’s assigned to a different variable. If function name is omitted, it will be the variable name. If function name is present, it will be the function name.

Difference between Function Expression and Function Declaration

The main difference between a function expression and a function declaration is the function name.

A function expression is very similar to function declaration and it has almost the same syntax as a function declaration.

//Function Expression
var foo = function() { return 5; } 
//ERROR! foo wasn't loaded yet
//Function Declaration example
function foo() { return 5; }
//Alerts 5.

So, as we can see in the examples above, Function declarations load before any code is executed while Function expressions load only when the interpreter reaches that line of code.

Arrow Function

Arrow functions allow us to write shorter function syntax.

For example,

fruit = () => {
  return "banana";

fruit(); // banana

It gets even shorter! If the function has only one statement, and the statement returns a value, we can remove the brackets and the return keyword. For example,

hello = () => "Hello World!";

If we want to pass parameters, we can pass them inside the parentheses or we can skip the parentheses if we have only one parameter. For example,

hello = (val) => "Hello " + val; OR hello = val => "Hello " + val;

What About this keyword?

Handling of this is also different in arrow functions compared to regular functions. With arrow functions there are no binding of this and this keyword always represents the object that defined the arrow function.

Let’s take a look at examples of both functions.

Example 1 demonstrates that in a regular function, the “this” keyword represents different objects depending on how the function was called.

Example 2 demonstrates that in Arrow Functions, the “this” keyword represents the object that owns the function, no matter who calls the function.

//Example 1

<button id="btn1">Click Me!</button>

<p id="example1"></p>

    var hello;

    hello = function() {
    document.getElementById("example1").innerHTML += this;

    //The window object calls the function:
    window.addEventListener("load", hello);

    //A button object calls the function:
    document.getElementById("btn1").addEventListener("click", hello);

[object HTMLButtonElement]

//Example 2

<button id="btn2">Click Me!</button>

<p id="example2"></p>

    var hello;

    hello = () => {
    document.getElementById("example2").innerHTML += this;

    //The window object calls the function:
    window.addEventListener("load", hello);

    //A button object calls the function:
    document.getElementById("btn2").addEventListener("click", hello);

[object Window]

Nested Functions

Prior to JavaScript 1.2, function definition was allowed only in top level global code, but JavaScript 1.2 allows function definitions to be nested within other functions as well.

All functions have access to the global scope. In other words, all functions have access to the scope “above” (outside) them. So, Nested functions have access to the scope “above” (outside) them.

In this example 1, the inner function plus() has access to the counter variable in the parent function.

<p id="demo">0</p>
document.getElementById("demo").innerHTML = add();
function add() {
     var counter = 0;
     function plus() {counter += 1;}
     return counter; 



Source: MDN and w3Schools


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Jul 22 Is there a CSS parent selector? #Jul 22 Difference between :where and :is in CSS #Jul 22 Does :is() pseudo selector hint at CSS preprocessing in the future? #Jul 22 Control Scrolling with CSS Scroll Snap #Jul 21 Control rendering using CSS content-visibility property #Jul 21 How to use @supports rule in CSS?
You might also like these
How to add AppRoutingModule in Angular application using command line?AngularHow to create a flip pricing table using CSS and JavaScript?CSSHow to CREATE TABLE in SQL with and without using Another Table?SQL/MySQLKilling A Project Part 1: What criteria should be used to cancel/kill a project?MiscellaneousHow to find the HCF or GCD and LCM of two given numbers using Swift?SwiftUnary Operators in JavaScriptJavaScript