Functions: The Backbone of Modular Codes-II

Learning Outcome

4

exploring IIFE (Immediately Invoked Function Expression) and its uses

3

exploring higher order function and its uses

2

understand what is first class function

1

understand pure and impure functions

Understanding Pure Functions For Predictable And Side-Effect-Free Code

A pure function always produces the same output for the same input and has no side effects

function income(salary){

  console.log(salary * 2);

}

income(20000);

CODE:

OUTPUT:

40000

Understanding Pure Functions For Predictable And Side-Effect-Free Code

A pure function always produces the same output for the same input and has no side effects

function income(salary){

  console.log(salary * 2);

}

income(20000);

CODE:

OUTPUT:

40000

Let's Explore The Difference Between Pure And Impure Functions

Pure Function

function income(salary){

  console.log(salary * 2);

}

income(20000);

  • Consistent Output: returns the same output for the same input
  • No Side Effects: Does not alter external state
  • Predictable Behavior: Easy to test and reason about

OUTPUT:

40000

What is First Class function?

A first-class function is a function that can be assigned to variables

const greet = function(name) {

    console.log("Hello " + name);

};

greet("Student")

OUTPUT:

Hello Student

What is Higher Order function?

A higher-order function is a function that takes functions as arguments, returns a function, or both

function repeat(action, times) {

for (let i = 0; i < times; i++) {

action();

}

}

// A simple function to be passed as an argument

function sayHello() {

console.log("Hello!");

}

// Using the higher-order function

repeat(sayHello, 3);

What is the key difference between the Higher order and First class function?

Higher Order Function 

Higher-order functions are specific functions that either take other functions as arguments or return them.

First Class Function

First-class functions describe the ability of functions to be treated like any other variable.

Discover The Magic Of Anonymous Functions In JavaScript

(function () {
    console.log("Welcome to ITVEDANT!");
})  ();

CODE:

OUTPUT:

Discover The Magic Of Anonymous Functions In JavaScript

(function () {
    console.log("Welcome to ITVEDANT!");
})  ();

This defines an unnamed function with code to execute

Quiz

Which of the following functions does NOT have a name?

A. Arrow function

B. Named function

C. Anonymous function

D. Constructor function

Quiz-Answer

A. Arrow function

B. Named function

C. Anonymous function

D. Constructor function

Which of the following functions does NOT have a name?

Functions: The Backbone of Modular codes-II

By Content ITV

Functions: The Backbone of Modular codes-II

  • 55