Higher order function in JavaScript

A function is a reusable piece of code introduced to avoid repetitive code and improve code readability and quality. In Javascript, functions are first-class citizens. Here we can take a function as an argument or return a function. This ability to accept and return a function makes it first class citizens in JavaScript. Higher order functions are functions that take a function as parameter and return a funcction as output.

Function as first-class citizens:

Some operations performed on functions in javascript which make it feel like first-class citizens are

  • Store function in a variable.
  • Store function in array.
  • Accept another function as argument or as a return from a function.
  • Set a function as object property.
Higher order functions:

A function which accepts another function as an argument or as a return from a function is higher order function.

Function that takes another function as argument:

A function which can be passed as an argument to another function is called callback functions. In javascript functions are objects, so they can be passed as an argument.

function getname(myname) {
  // Invoke the passed function
  myname();
}

// Invoke the function by passing a function as an argument
getname(function(){
  console.log('Abaython');
});

Output:Abaython
Return function:

Here a function is returned from a function.

// Define a function that returns a function
function returnFunc() {
  return function() {
    console.log('Abaython');
  }
}

// Take the returned function in a variable.
const fn = returnFunc();
// Now invoke the returned function.
fn(); // Abaython
// Alternatively 
returnFunc()(); // Abaython
Output:

Abaython

Abaython

In JavaScript we have forEach(), map(), reduce() and filter() functions which are built-in higher order functions.

.forEach():

Iterate through an array of elements. It is used only with arrays. It takes a callback function with elements, index and array.

let sum = 0;
const numbers = [10, 20, 30, 40, 50];
numbers.forEach(num => sum+=num)
console.log(sum);
Output: 150
map():

Iterate an array and modify the elements of array. It takes a callback function with elements, index, array parameter and return a new array.

const num = [10, 20, 30, 40, 50]
const double = num.map((num) => num + num)
console.log(double)
Output: [ 20, 40, 60, 80, 100 ]
filter():

filter a set of elements which satisfies a certain condition and return a new array.

const num = [10, 20, 30, 40, 50]
const num1 = num.filter((num) => num>30)
console.log(num1)
Output: [ 40, 50 ]
reduce():

The reduce method executes the callback function on each member of the calling array which results in a single output value. The reduce method accepts two parameters: The reducer function (callback) and an optional initialValue.

The callback function  in turn accepts the following four parameters:

  • Accumulator
  • Current value
  • Current index
  • Source array
const num = [10, 20, 30, 40, 50]
const sum = num.reduce((acc, cur) => acc + cur, 0)
console.log(sum)
Output: 150

In a nutshell, higher order function are helpful in making a cleaner, readable and quality code.

7 Data Structures in JavaScript you need to know.

In this article, let’s try to understand the important data structures in javascript.

What is a Data Structure?

Data Structure is a storage that is used to store and organize data. It is a way of storing and organizing the data in such a way that it can be accessed more efficiently. It refers to group of data values, the relationship between them and the operations that can be performed on it. JavaScript has dynamic arrays i.e their size and type are not determined.

Now let us jump into the data structures in javascript.

1.Array Data Structure

Most popular linear data structure. All the elements are of same data type and stored in contiguous memory location. An array is represented by set of elements with index.

2.Stack Data Structure

Stack works on Last in First out(LIFO) principle. It is a linear data structure. It contains only one pointer and that points to the top element or last added element of the stack. Whenever we add or delete an element it is added or deleted from the top. Like a pile of books.

3.Queue Data Structure

Queue works on the principle of First in First out(FIFO). It is a linear data structure. It contains two-pointers front pointer and rear pointer. The front pointer contains address of the starting element and rear pointer contains address of the last element. The two main methods used for implementation. Enqueue is process of adding an element in the queue and dequeue is process of removing an element from the queue.

4.Linked List

Linked list is a linear data structure and here unlike arrays elements are stored in non-contiguous memory locations. It is made of group of nodes. Each node has its own data and address to the next node.

Here in linked list you have to start from head and work through the way to desired element. First element is head and last element is tail.

  • List don’t have indexes, so we cannot access elements randomly.
  • Insertion and deletion is more efficient we have to just redirect the pointers.

5.Trees

Tree is a non-linear data structure which consists of nodes connected by edges. This data structure link nodes via parent/child relationship. The top node is called root node and all the other nodes come off that node are called children. The nodes at the bottom of the tree are called leaf nodes. The height of the tree is determined by number of parent/child relationships it has.

Points to note:
  • A connection is valid between nodes when it is from parent to child.
  • Connection between siblings or child to parent are not valid.
  • Tree must have only one root node.
Examples:
  • File folders in our operating system
  • DOM model
Popular Tree based data structure
  • Binary Tree
  • Binary Search Tree
  • AVL Tree
  • Red-Black Tree
  • N-ary Tree
  • 2-3 Tree

6.Graph Data Structure

Graphs are relation based data structure helpful in storing web-like or network relationships. It is made up of a finite collection of nodes called vertices, and the connections between them are known as edges. Graphs can be of two types: Directed graph and undirected graph.

Often used in Social networks, geolocalization(Google maps) and Web analytics.

7.Hash table

Hash table is also known as hash map or hash. Generally used in Object data structures, map or dictionary as it queries through a key and hash function. Hashing is a technique of mapping keys, values into the hash table using a hash function. Key is a searched string and value is the data paired with the key. Insertion and search function are very fast irrespective of the size of the table. Hash tables are built using arrays. In real life example of hash table is in schools each student is assigned a unique id number.