How and why to use Functional Programming in modern JavaScript

How and why to use Functional Programming in modern JavaScript

In this article, you will get a deep understanding of functional programming and its benefits.

In this article, you will get a deep understanding of functional programming and its benefits.

Introduction To Functional Programming

Functional programming (FP) is a type of paradigm or pattern in computer science. Everything is done with the help of functions in FP and the basic building blocks are functions only.

Programming languages that support purely functional programming are —

  1. Haskell
  2. Closure
  3. Scala
  4. SQL

Some of the programming languages that support functional programming as well as other programming paradigms are —

  1. Python
  2. Javascript
  3. C++
  4. Ruby

Since the name says functional, most of the programmers think about Mathematical functions. That is not the case with FP. It is just an abstraction to solve real-world complex problems in an easy and effective manner.

Before the Object-Oriented programming Era, the software industry completely depended on functional programming. This paradigm rocked the software industry for a couple of decades. There are some issues with functional programming, and that’s why they moved to Object-Oriented paradigm. The issues with FP will be discussed later in this article.

That is all about the introduction to Functional Programming. Now, first of all, we need to learn what is a function.

Functions

Before revealing the actual definition, I want to explain a situation to know where to actually use FP. Suppose you are writing code to build an application. In your development journey, you want to reuse the code of a few lines (100) at different places. For your Application, functions are helpful. We can write functions at one place and we will be able to access those functions from anywhere in the program. Functional programming has the following features —

  1. Reduces code redundancy.
  2. Improves modularity.
  3. Helps us to solve complex problems.
  4. Increases maintainability.

Let’s look at the actual definition of a function:

A Function is a specified block of code which is used to perform a specific task in the program.

The most popular types of functions are —

  1. General Functions
  2. Arrow Functions
  3. Anonymous Functions

General Functions

General functions are nothing but the functions that are quite often used by the programmer to perform a specific task. The syntax to declare a general function in Javascript is:

function functionName(parameters) {  // code to be executed}

function — It is a keyword which is necessary to declare a function.

**functionName — **It can be named based on the function work.

parameters — We can pass any number of parameters to a function.

A Function is a specified block of code which is used to perform a specific task in the program.
We need to call the function when we want to execute that piece of code that is returned within a function.

The general functions are classified as follows —

No-Argument Functions

We don’t need to pass any arguments to the function.

// Function Declaration
function sayHello(){   alert('Hello...!');}
// Calling the functionsayHello()

When we call the function to sayHello() it will produce the alert message as Hello.

Argument Functions

In this type of functions, we will pass arguments to them.

Example

// Declaring a Function
function add(num1, num2){   return num1 + num2;}
// Function Call
var result = add(7, 11);
console.log(result);

The arguments that are passed while declaring a function i.e (num1, num2) are called as*** Formal Parameters.***

The arguments that are passed while calling a function i.e (7, 11) are called as Actual Parameters.

A Function usually returns some value, and to return that value we need to use return keyword. When a function is returning some value it means it doesn’t print any output for us, it just returns the final output. It is our responsibility to print that result. In the above program, the function is returning the value and I’m passing that value to a variable name ‘result’. Now the function will pass the result to the ‘result’ variable.

The speciality of Javascript Functions

If you pass more arguments than the declared number, then you will not get any error. But in other programming languages like Python, C, C++, Java, etc… we will get an error. Javascript will consider based on their requirements.

Example

// Calling the function with more number of arguments than the declared number
var result1 = add(2, 4, 6);console.log(result1);
var result2 = add(2);console.log(result2);

Output

Output and Execution of the above program in chrome Javascript console.

If you pass fewer arguments than the declared number, then also we will not get any error. But we can’t predict the output for the program because, based on your function functionality, the output will be produced.

Variable Argument Function

The greatest advantage of Javascript functions is we can pass any number of arguments to the function. This feature helps developers to work more effectively in a consistent manner.

Example

// Creating a function to calculate sum of all argument numbers
function sumAll(){
let sum = 0;
for(let i=0;i<arguments.length;i++){      sum = sum + arguments[i];}
return sum;
}
// Calling the sumAll function
sumAll();
sumAll(1,2,3,12,134,3234,4233,12,3243);

Output

Output and Execution part of the above program in chrome Javascript console.

This is all about general functions that are used to perform our complex task in a simple manner. Now let’s discuss some advanced functions introduced in ES6 called** Arrow Functions**.

Arrow Functions

An arrow function expression is a syntactically compact alternative to a regular function expression. It doesn’t have its own bindings to the thissuperarguments or new.target keywords. Arrow function expressions are ill-suited as methods. They cannot be used as constructors.

A Function is a specified block of code which is used to perform a specific task in the program.
The syntax for the arrow function is:

const functionName = (parameters) => {  // code to be executed}
           (OR)
var functionName = (parameters) => {  // code to be executed}
           (OR)
let functionName = (parameters) => {  // code to be executed}

Examples for Arrow Functions

Eg 1

Creating an Arrow function to say a welcome message to the users.

// Creating a Welcome function
let sayHello = () => {   return 'Welcome to Javascript World...!';}
// Calling the function
console.log(sayHello())

Output

Output and Execution part of the above program in chrome Javascript console.

Eg 2

In this example, we are creating an Arrow function to generate the greatest of all numbers that are passed as an argument.

let maxNumber = (a,b,c,d) => {
   if(a > b && a > c && a > d)       return a;   else if(b > a && b > c && b>d)       return b;   else if(c > a && c > b && c > d)       return c;   else       return d;}
// Calling the function
console.log(maxNumber(1,2,4,3));

Output:

Output and Execution part of the above program in chrome Javascript console.

Combination of Variable Arguments with Arrow Functions

Since we are working with an arrow function, it doesn’t support the arguments array by default like general function. It is our responsibility to declare explicitly that it supports the variable number of arguments

Eg 3

let varArgSum = (...args) => {   let sum = 0;
 for(let i=0;i<args.length;i++){      sum = sum + args[i];}
return sum;
}
// Calling the Function
console.log(varArgSum());
console.log(varArgSum(1,2,3,4,5,6,7,8,9,10));

Output

Output and Execution part of the above program in chrome Javascript console.

This is how we can combine a variable number of arguments with arrow functions. Now let’s discuss Anonymous functions in JavaScript.

Anonymous Functions

An anonymous function is simply a function with no name. The purpose of using anonymous function is to perform a certain task and that task is no longer required to program. Generally, anonymous functions are declared dynamically at run time.

A Function is a specified block of code which is used to perform a specific task in the program.
Example:

// Working with an Anonymous function
var a = 10;  // Global Scope Variable.
// creating a function(function() {
  console.log("welcome to the world of Anonymous function");
  var b = 20;  // b is a local scope variable.
  var c = a+b; // c is a local scope variable    //a can be used because it is in the global scope
  console.log("Addition of two numbers value is: "+c);})();

Output

Output and Execution part of the above program in chrome Javascript console.

This is the concept of anonymous functions. I think I explained it in a simple and easy way.

Higher Order Functions

A higher-order function is a function that takes functions as an argument or that returns another function as a result.

The best example of higher-order functions in Javascript is that of Array.map(), Array.reduce(), Array.filter().

Example 1: Array.map()

// working with Array.map()
let myNumberArray = [4,9,16,25,36,49];
let mySquareRootArray = myNumberArray.map(Math.sqrt);
console.log(mySquareRootArray);

Output

Output and Execution part of the above program in chrome Javascript console.

Example 2: Array.reduce()

// working with Array.reduce()
let someRandomNumbers = [24,1,23,78,93,47,86];
function getSum(total, num){  return total + num;}
let newReducedResult = someRandomNumbers.reduce(getSum);
console.log(newReducedResult);

Output

Output and Execution part of the above program in chrome Javascript console.

Example 3: Array.filter()

// Working with array filter
let ages = [12,24,43,57,18,90,43,36,92,11,3,4,8,9,9,15,16,14];
function rightToVote(age){   return age >= 18;}
let votersArray = ages.filter(rightToVote);
console.log(votersArray);

Output

Output and Execution part of the above program in chrome Javascript console.

Recursion

This is one of the key topics in functional programming. The process in which a function calls directly or indirectly is called a recursive function. This concept of recursion is quite useful in solving algorithmic problems like the Towers of Hanoi, Pre-Order, Post-Order, In-Order, and some graph traversal problems.

Example

Let’s discuss a famous example: finding the factorial of a number using recursion. This can be done by calling the function directly from the program repeatedly. The logic for the program is

A Function is a specified block of code which is used to perform a specific task in the program.

// Finding the factorial of a number using Recursion
function factorial(num){  if(num == 0)        return 1;  else        return num * factorial(num - 1);
}
// calling the function
console.log(factorial(3));
console.log(factorial(7));
console.log(factorial(0));

Output

Output and Execution part of the above program in chrome Javascript console.

Characteristics Of Functional Programming

The objective of any FP language is to mimic the use of mathematical concepts. However, the basic process of computation is different in functional programming. The major characteristics of functional programming are:

**Data is immutable: **The data which is present inside the functions are immutable. In Functional programming, we can easily create a new Data structure but we can’t modify the existing one.

**Maintainability: **Functional programming produces great maintainability for developers and programmers. We don’t need to worry about changes that are accidentally done outside the given function.

**Modularity: **This is one of the most important characteristics of functional programming. This helps us to break down a large project into simpler modules. These modules can be tested separately which helps you to reduce the time spent on unit testing and debugging.

Advantages Of Functional Programming

1.It helps us to solve problems effectively in a simpler way.
2. It improves modularity.
3. It allows us to implement lambda calculus in our program to solve complex problems.
4. Some programming languages support nested functions which improve maintainability of the code.
5. It reduces complex problems into simple pieces.
6. It improves the productivity of the developer.
7. It helps us to debug the code quickly.

Disadvantages Of Functional Programming

  1. For beginners, it is difficult to understand. So it is not a beginner friendly paradigm approach for new programmers.
  2. Maintainance is difficult during the coding phase when the project size is large.
  3. Reusability in Functional programming is a tricky task for developers.

Conclusion

For some, it might be a completely new programming paradigm. I hope you will give it a chance in your programming journey. I think you’ll find your programs easier to read and debug.

This Functional programming concept might be tricky and tough for you. Even if you are a beginner, it will eventually become easier. Then you can enjoy the features of functional programming.😎🤓

If you liked this article, please click on the clap, leave me your valuable feedback, and share with your friends.

Hello busy people, I hope you had fun reading this post, and I hope you learned a lot here! This was my attempt to share what I’m learning.

JavaScript Tutorial: if-else Statement in JavaScript

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.

JavaScript’s conditional statements:

  • if
  • if-else
  • nested-if
  • if-else-if

These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:
if(condition) 
{
   // Statements to execute if
   // condition is true
}

Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,

if(condition)
   statement1;
   statement2;

// Here if the condition is true, if block 
// will consider only statement1 to be inside 
// its block.

Flow chart:

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If statement 

var i = 10; 

if (i > 15) 
document.write("10 is less than 15"); 

// This statement will be executed 
// as if considers one statement by default 
document.write("I am Not in if"); 

< /script> 

Output:

I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:
if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}


Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If-else statement 

var i = 10; 

if (i < 15) 
document.write("10 is less than 15"); 
else
document.write("I am Not in if"); 

< /script> 

Output:

i is smaller than 15
  • nested-if A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:
if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      // Executes when condition2 is true
   }
}

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate nested-if statement 

var i = 10; 

if (i == 10) { 

// First if statement 
if (i < 15) 
	document.write("i is smaller than 15"); 

// Nested - if statement 
// Will only be executed if statement above 
// it is true 
if (i < 12) 
	document.write("i is smaller than 12 too"); 
else
	document.write("i is greater than 15"); 
} 
< /script> 

Output:

i is smaller than 15
i is smaller than 12 too
  • if-else-if ladder Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;


Example:

<script type = "text/javaScript"> 
// JavaScript program to illustrate nested-if statement 

var i = 20; 

if (i == 10) 
document.wrte("i is 10"); 
else if (i == 15) 
document.wrte("i is 15"); 
else if (i == 20) 
document.wrte("i is 20"); 
else
document.wrte("i is not present"); 
< /script> 

Output:

i is 20

How to Retrieve full Profile of LinkedIn User using Javascript

How to Retrieve full Profile of LinkedIn User using Javascript

I am trying to retrieve the full profile (especially job history and educational qualifications) of a linkedin user via the Javascript (Fetch LinkedIn Data Using JavaScript)

Here we are fetching LinkedIn data like Username, Email and other fields using JavaScript SDK.

Here we have 2 workarounds.

  1. Configuration of linkedIn developer api
  2. Javascript Code to fetch records

Configuration of linkedIn developer api

In order to fetch records, first we need to create developer api in linkedin which will act as token/identity while fetching data from other linkedin accounts.

So to create api, navigate to https://linkedin.com/developer/apps and click on 'Create Application'.

After navigating, fill in details like name, description and other required fields and then submit.

As we submit, it will create Client ID and Client Secret shown below, which we will be using in our code while communicating to fetch records from other LinkedIn account.

Note: We need to provide localhost Url here under Oauth 2.0. I am using my localhost, but you can probably use other production URLs under Oauth 2.0 where your app is configured. It will make your api  consider the Url as trusted which fetching records.

Javascript Code to fetch records

For getting user details like first name, last name,User image can be written as,

<script type="text/javascript" src="https://platform.linkedin.com/in.js">  
    api_key: XXXXXXX //Client ID  
    onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load  
    authorize: true  
</script>  
<script type="text/javascript">  
    function OnLinkedInFrameworkLoad() {  
        IN.Event.on(IN, "auth", OnLinkedInAuth);  
    }  
  
    function OnLinkedInAuth() {  
        IN.API.Profile("me").result(ShowProfileData);  
    }  
  
    function ShowProfileData(profiles) {  
        var member = profiles.values[0];  
        var id = member.id;  
        var firstName = member.firstName;  
        var lastName = member.lastName;  
        var photo = member.pictureUrl;  
        var headline = member.headline;  
        //use information captured above  
        var stringToBind = "<p>First Name: " + firstName + " <p/><p> Last Name: " + lastName + "<p/><p>User ID: " + id + " and Head Line Provided: " + headline + "<p/>"  
        document.getElementById('profiles').innerHTML = stringToBind;  
    }  
</script>    

Kindly note we need to include 'https://platform.linkedin.com/in.js' as src under script type as it will act on this Javascript SDK provided by Linkedin.

In the same way we can also fetch records of any organization with the companyid as keyword.

<head>  
    <script type="text/javascript" src="https://platform.linkedin.com/in.js">  
        api_key: XXXXXXX ////Client ID  
        onLoad: onLinkedInLoad  
        authorize: true  
    </script>  
</head>  
  
<body>  
    <div id="displayUpdates"></div>  
    <script type="text/javascript">  
        function onLinkedInLoad() {  
            IN.Event.on(IN, "auth", onLinkedInAuth);  
            console.log("On auth");  
        }  
  
        function onLinkedInAuth() {  
            var cpnyID = XXXXX; //the Company ID for which we want updates  
            IN.API.Raw("/companies/" + cpnyID + "/updates?event-type=status-update&start=0&count=10&format=json").result(displayCompanyUpdates);  
            console.log("After auth");  
        }  
  
        function displayCompanyUpdates(result) {  
            var div = document.getElementById("displayUpdates");  
            var el = "<ul>";  
            var resValues = result.values;  
            for (var i in resValues) {  
                var share = resValues[i].updateContent.companyStatusUpdate.share;  
                var isContent = share.content;  
                var isTitled = isContent,  
                    isLinked = isContent,  
                    isDescription = isContent,  
                    isThumbnail = isContent,  
                    isComment = isContent;  
                if (isTitled) {  
                    var title = isContent.title;  
                } else {  
                    var title = "News headline";  
                }  
                var comment = share.comment;  
                if (isLinked) {  
                    var link = isContent.shortenedUrl;  
                } else {  
                    var link = "#";  
                }  
                if (isDescription) {  
                    var description = isContent.description;  
                } else {  
                    var description = "No description";  
                }  
                /* 
                if (isThumbnailz) { 
                var thumbnailUrl = isContent.thumbnailUrl; 
                } else { 
                var thumbnailUrl = "http://placehold.it/60x60"; 
                } 
                */  
                if (share) {  
                    var content = "<a target='_blank' href=" + link + ">" + comment + "</a><br>";  
                    //el += "<li><img src='" + thumbnailUrl + "' alt=''>" + content + "</li>";  
                    el += "<li><div>" + content + "</div></li>";  
                }  
                console.log(share);  
            }  
            el += "</ul>";  
            document.getElementById("displayUpdates").innerHTML = el;  
        }  
    </script>  
</body>  

We can get multiple metadata while fetching records for any any organization. We can get company updates as shown below.

Conclusion

We can also fetch any company specific data like company job updates/post, total likes, comments, and number of views along with a lot of metadata we can fetch which I have shown below.

Thank you for reading !

7 Best Javascript Iframe Libraries

7 Best Javascript Iframe Libraries

Iframes let you build user experiences into embeddable ‘cross-domain components’, which let users interact with other sites without being redirected. I have compiled 7 best Javascript iframe libraries.

Iframes let you build user experiences into embeddable ‘cross-domain components’, which let users interact with other sites without being redirected. I have compiled 7 best Javascript iframe libraries.

1. Zoid

A cross-domain component toolkit, supporting:

  • Render an iframe or popup on a different domain, and pass down props, including objects and functions
  • Call callbacks natively from the child window without worrying about post-messaging or cross-domain restrictions
  • Create and expose components to share functionality from your site to others!
  • Render your component directly as a React, Vue or Angular component!
    It's 'data-down, actions up' style components, but 100% cross-domain using iframes and popups!

Download


2. Postmate

Postmate is a promise-based API built on postMessage. It allows a parent page to speak with a child iFrame across origins with minimal effort.

Download


3. Iframe Resizer

Keep same and cross domain iFrames sized to their content with support for window/content resizing, in page links, nesting and multiple iFrames

Demo

Download


4. Iframely

Embed proxy. Supports over 1800 domains via custom parsers, oEmbed, Twitter Cards and Open Graph

Demo

Download


5. React Frame component

This component allows you to encapsulate your entire React application or per component in an iFrame.

Demo

Download


6. Seamless.js

A seamless iframe makes it so that visitors are unable to distinguish between content within the iframe and content beside the iframe. Seamless.js is a JavaScript library (with no dependencies) that makes working with iframes easy by doing all the seamless stuff for you automatically.

Demo

Download


7. Porthole

A proxy to safely communicate to cross-domain iframes in javascript

Demo

Download


Thank for read!