From Traditional to Modern: Understanding of JavaScript Functions

Introduction

Functions lie at the heart of JavaScript, serving as versatile tools for structuring code, encapsulating logic, and enabling reusability.

Functions make your code easier to understand. Instead of writing the same code again and again, you can write a function for that job and use it whenever you need to. It's like having a recipe for making cookies—you don't have to remember all the steps each time you want to bake.

So in this Article, we are going to cover the types of functions in Javascript -

  • Named Functions
  • Anonymous Functions
  • Arrow Functions
  • Immediately Invoked Functions Expressions(IIFE)
  • Callback Functions
  • Higher Order Functions
  • Constructor Functions

Named Functions

These functions are the traditional way as you all must know, using the function keyword followed by a name that can be used as a callback to that function.

Named functions in JavaScript are like predefined recipes. Each recipe has a name (the function name) and contains instructions (the function code) for a specific cooking task.

// define the named function called firstfunction 
function makePancakes() {
  // Instructions for making pancakes
  console.log("1. Mix flour, eggs, milk, and sugar.");
  console.log("2. Pour batter onto a hot griddle.");
  console.log("3. Flip the pancakes when bubbles form.");
  console.log("4. Cook until golden brown on both sides.");
}
makePancakes();

Output

1. Mix flour, eggs, milk, and sugar.
2. Pour batter onto a hot griddle.
3. Flip the pancakes when bubbles form.
4. Cook until golden brown on both sides.

Anonymous functions

Unlike named functions, anonymous functions don’t have a name and are commonly created on the spot for immediate use wherever necessary. , these are used as function expressions or arguments.

It's just like secret agents—they do their job without leaving a trace

var secondfunction = function(name){
console.log('Hello ' +name);
}

secondfunction('Abhishek'); 

Output

Hello Abhishek

// Adding an event listener with an anonymous function

document.getElementById("myButton").addEventListener("click", function() {
  console.log("Button clicked!");
});

Arrow Functions

Ideal for shorter syntax and one-liner function or single expression function

var thirdfunction = () =>console.log(' Arrow function called');
thirdfunction();

Output

Arrow function called

let greet = (name) => {
  return "Hello, " + name + "!";
};

let message = greet("Abhishek");

console.log(message)

Output

Hello, Abhishek!

Immediately Invoked functions expressions(IIFE)

Executed immediately after their creation.

IIFEs are often used to create a new scope for variables and functions, preventing them from polluting the global scope. They are also commonly used in modular JavaScript to encapsulate code and avoid naming conflicts.

(function() {
  console.log("This is an IIFE!");
})();

Output

This is an IIFE!

Callback Functions

The function passed as an argument to another function called a callback function.

function greet(name,callback){
console.log("Hello," +name +"!");
callback();
}
function saygoodbye(){
console.log("GOodbye!");
}
greet("Abhishek",saygoodbye);

Output

Hello,Abhishek!
GOodbye!

Higher order functions

That take one or more functions as arguments or return a function as their result, Empowering functional programming techniques like

  • map
  • filter
  • reduce

Map()

Map transforms each element of an array using a provided function and returns a new array with the transformed elements.

// Doubling each element in an array using map.

let numbers = [1, 2, 3, 4, 5];
let doubledNumbers = numbers.map(function(num) {
  return num * 2;
});

console.log(doubledNumbers);

Output

[2, 4, 6, 8, 10]

filter()

Filter creates a new array containing only the elements of the original array that satisfy a provided function.

// Filtering even numbers from an array using filter.

let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(function(num) {
  return num % 2 === 0;
});
console.log(evenNumbers);

Output

[2, 4]

reduce()

Reduce applies a function to each element of an array, resulting in a single output value. It "reduces" the array to a single value.

// Summing all elements in an array using reduce

let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce(function(acc, num) {
  return acc + num;
}, 0);
console.log(sum); 

Output

15

Constructor functions

Used as blueprints for creating objects with similar properties and methods. They are invoked using the new keyword to create instance of objects.

// Constructor function for Person objects
function Person(first, last, age) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
}

const myFriend1 = new Person("Rahul", "Kumar", 22);
const myFriend2 = new Person("Saurav", "Kumar", 28);

console.log("My first Friend age is " + myFriend1.age + ". My second Friend age is " + myFriend2.age + ".");

Output

My first Friend age is 22. My second Friend age is 28.

Conclusion

Grasping the various types of functions in JavaScript is key to crafting code that's clear, efficient, and easy to maintain. Whether you're using the familiar named functions or the newer arrow functions, understanding their differences and when to use each one can greatly enhance your coding skills.