Progressive Full Stack Application Development with Live Projects

JavaScript

JavaScript Functions

JavaScript Functions
  • Learn about Functions in JavaScript Programming

1. Basics of JavaScript Functions

What are Functions?

  1. A function is a reusable block of code written to perform a specific task.
  2. It can take inputs, process those inputs, and return the results.

Function Declaration

  • A function consists of a name, body or function block.
  • A function is defined with the function keyword.
  • The function keyword is important when working with function declaration.

Function Expression

  • Apart from declaring functions, JavaScript supports function expressions.
  • A function assigned to a variable.
  • Note that a function expression is not hoisted, so it can only be called after it’s defined.

Function to add two numbers

JavaScript
function add(){
return 2+3;
}

Above function named add will add two fixed numbers that is written in function logic. We need a function that can accept these numbers as a parameter. JavaScript functions accepts any number of comma separated parameters inside the bracket.


Example 1: Function to add two given numbers

JavaScript
function add(a, b){
return a+b;
}

This is a better version of a function that adds any two numbers that is given to it as parameters.


Function to add all numbers in an array

JavaScript
function add(numbers){
let sum = 0;
for (const el of numbers) {
  sum += el;
}
return sum;
}

Calling Functions

After declaring a function, you must call it for execution. The executive function should be in scope(scope determines the accessibility) when it is called.

It is not necessary to call a function after function declaration. you can call it before the function declaration. This is called hoisting in JavaScript.

Function declarations can be hoisted i.e they can be called before the function is being defined.


2. JavaScript Functions as Objects

Functions in JS are First Class objects

A First-Class Citizen in a programming language is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as any other variables in the programming language. In JavaScript, Functions are just like objects. The only difference is that functions can be called but objects are not. So the following hold true for a JS function.

  • Functions can be assigned to a variable
  • Functions can be assigned a property just like objects
  • A function can be passed as an argument to a function
  • A function can be returned from a function

3. Different Types of JavaScript Functions

3.1 Callback Functions


Callbacks are functions passed as arguments to another function, and they are executed once the operation is completed.

function fetchData(callback) {
  // Simulating some asynchronous operation
  setTimeout(function() {
    const data = "Some data";
    callback(null, data); // Passing error & success data
  }, 1000);
}

// Using the fetchData function with a callback
fetchData(function(error, data) {
  if (error) {
    console.error("Error:", error);
  } else {
    console.log("Data:", data);
  }
});
  • fetchData() is a function that takes a function and calls it with parameters (indicating success and failure) after a delay of 1 second.
  • Have a look at Line 10, there is an unnamed function passed to the function fetchData, this is a callback function.

3.2 Immediately invoked functional Expressions (IIFE)


Immediately Invoked Function Expressions (IIFE) are JavaScript functions that are defined and immediately invoked. They are wrapped in parentheses to turn them into expressions and followed by an additional pair of parentheses to invoke them immediately after declaration.

Syntax of IIFE:

(function (){ 
// IIFE Logic Here
})();

Simple Example of IIFE:

let result = (function() {
    var x = 20;
    var y = 30;
    return x + y;
})();

//Calling the function
console.log(result); // Output: 50

Explanation: The anonymous (unnamed) function in example above is wrapped in parentheses (function() { ... }), followed by () to immediately invoke it.

Why should we use IIFE?

IIFE is a design pattern also known as a Self-Executing Anonymous Function. In a real application there could be many functions and global variables from different source files, it’s important to limit the number of global variables. IIFEs can be helpful in such scenarios over function declarations and function expressions.

  • IIFEs are commonly used to create a new type of private scope in JavaScript, allowing variables and functions to be encapsulated and inaccessible from outside the function. Thus creating self-contained modules.
  • IIFEs create a new scope, preventing variable hoisting and avoiding polluting the global scope.
  • It is used to execute the async and await function.

3.3 Arrow Functions


An arrow function is an anonymous function with a shorter syntax.

  • Arrow functions are just syntactic sugar from ES6 (6th version of ECMAScript), to make the code shorter and more readable.
  • Arrow function lexically binds to the surrounding scope. i.e. Arrow Functions inherit this from the surrounding lexical context, making them useful for methods inside objects or for maintaining the context of callbacks.

Syntax of Arrow Function:

const myArrowFunction = () => {
    console.log( "Printed inside arrow function" );
}

Examples of Arrow Function:

1. Single Parameter Arrow Functions: If an arrow function has a single parameter, we can omit the parentheses around it.

//Arrow function with single parameter
const square = x => x*x;

2. Multiple Parameter Arrow Functions: This arrow function takes 3 parameters.

const add = ( x, y, z ) => {
    console.log( x + y + z )
}
//call the function
add( 10, 20, 30 );

3. Returning Objects from Arrow Functions: This arrow function accepts parameters firstName, lastName and returns an object.

const createPerson = (firstName, lastName) =>
({first: firstName, last: lastName});

//calling function
console.log(createPerson("Mahesh", "Sood"));

Advantages

Benefits of Arrow Functions

  • Concise Syntax: Arrow functions reduce the amount of code needed for function expressions.
  • Lexical this Binding: Arrow functions automatically bind this to the surrounding context, eliminating common issues when dealing with callbacks.
  • Improved Readability: Arrow syntax can make code easy to read.

Note: Arrow functions are similar to lambda functions in some other programming languages.

Leave a Reply