Mark As Completed Discussion

What is functional programming?

Functional programming is a programming paradigm just like object-oriented programming and procedural programming. It follows a declarative programming style rather than an imperative programming style.

To put it simply, declarative programming is like asking your friend to fix your computer, but you don’t care how he or she does it. In imperative, each and every step of the process is detailed.

Suppose we have the following basket of food:

JAVASCRIPT
1const basket = [
2    {
3        name: "mango",
4        type: "fruit"
5    },
6    {
7        name: "onion",
8        type: "vegetable"
9    },
10    {
11        name: "potato",
12        type: "vegetable"
13    },
14    {
15        name: "apple",
16        type: "fruit"
17    }
18];

Let’s take a look at an imperatively written program. We have a basket of fruits and vegetables and we want to segregate the fruits into a different basket. This could be a simple program and you may already have the following solution in mind.

JAVASCRIPT
1function findFruit(basket){
2    let fruits = [];
3    for(let i = 0; i < basket.length; i++){
4        const item = basket[i]
5        if(item.type == "fruit"){
6            fruits.push(item);
7        }
8    }
9    return fruits;
10}
11
12let fruits = findFruit(basket);
13console.log(fruits);

The example above is done through imperative programming. We use a loop to find the one of interest and add it to a new array and return the new array. Now, using declarative programming, the same function would be written in the following way.

This is declarative programming. From 8 lines of code, it has come down to just 2 lines of code. We are making use of the filter function on the array without having to go through each item in the basket because we are not worried about how it is implemented but only about the end result.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment