YogeshChauhan . com

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('YogeshChauhan.com')); // YogeshChauhan.com

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.name // "foo"

var foo2 = foo
foo2.name // "foo"

var bar = function baz() {}
bar.name // "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 uninstall Cocoapods from the Mac OS? #4 How to add Read More Read Less Button using JavaScript? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

May 5 Use inline if to make a shorter conditional syntax in React May 4 What is Conditional Rendering in React? May 3 How does @extend rule work in SCSS (Sass)? May 2 How different is Handling Events in React vs HTML DOM? May 2 How to create bouncing balls using HTML canvas and JavaScript? Apr 30 HTML canvas methods

You might also like these

How does Binding work in JavaScript?JavaScriptWhat is iFrame in HTML? Why do we need it?HTMLWhat are Null Sessions?MiscHow to change HTML content on click using JavaScript?JavaScriptHow to get user’s Browser and Operating Systems information using PHP?PHPIntroduction to components and templates Part 4: Pipes and DirectivesAngular