Asynchronous JavaScript

Asynchronous JavaScript

In this article, we are going to discuss asynchronous tasks in significant depth. We will be discussing what exactly asynchronous tasks are, what the hack callbacks are, closures, promises, and much more in the context of JavaScript.

In this article, we are going to discuss asynchronous tasks in significant depth. We will be discussing what exactly asynchronous tasks are, what the hack callbacks are, closures, promises, and much more in the context of JavaScript.

We take a deep dive into asynchronous and how the JavaScript language uses this code execution paradigm.

Table of Contents

    1. Prerequisites
    1. Overview
    1. Callbacks in JavaScript
    1. Hitting HTTP Requests in JavaScript
    1. Callback Abstraction
    1. Closures
      Method Currying* 7. Promises
      Short-Hand Syntax for PromisesPromise ChainingFetch APIAsync-Await## Prerequisites to Understand Asynchronous Concepts
    1. Prerequisites
    1. Overview
    1. Callbacks in JavaScript
    1. Hitting HTTP Requests in JavaScript
    1. Callback Abstraction
    1. Closures
      Method Currying* 7. Promises
      Short-Hand Syntax for PromisesPromise ChainingFetch APIAsync-Await## Overview: What Exactly Does it Mean to Perform Tasks Asynchronously?

As Google says, asynchronous is ‘not existing or occurring at the same time.’ When we execute something synchronously, we start some sort of task like fetching a weather report from some third-party server and then we have to wait for it to finish before we move on to the next thing. When we execute something asynchronously, we can start some task, then we can actually get other work done before the task completes_, _and that’s the beauty of performing tasks asynchronously.

Callbacks in JavaScript

Callbacks are simply functions in JavaScript which are to be called and then executed after the execution of another function has finished. So how does it happens Actually, in JavaScript, functions are considered objects and, thus, all other objects, even functions, can be sent as arguments to other functions. The most common and generic use case one can think of is the setTimeout() function in JavaScript.

Consider the following example:

 //with customary function signature  
 setTimeout(function() {  
   console.log('hello1');  
 }, 1000);  
 //with arrow function signature  
 setTimeout(() => {  
   console.log('hello2');  
 }, 2000);  

I have used the setTimeout() function by passing a callback function as an argument into it along with the second argument which is simply the number of milliseconds after which our callback function is executed. I have shown two ways of passing a callback function here, one is the more of customary approach and the second one is the arrow function approach which is more modern.

Sending HTTP Requests in JavaScript

Suppose I want to send an HTTP request to an API which fetches some random text for me. We won’t be digging much into the details of sending HTTP requests, as this is out of the scope of this article.

Now, to hit that API, you need to create two files:

    1. Prerequisites
    1. Overview
    1. Callbacks in JavaScript
    1. Hitting HTTP Requests in JavaScript
    1. Callback Abstraction
    1. Closures
      Method Currying* 7. Promises
      Short-Hand Syntax for PromisesPromise ChainingFetch APIAsync-Await
 <!DOCTYPE html>  
 <html>  
   <head></head>  
   <body>  
     <script src="app.js"></script>  
   </body>  
 </html>  

    1. Prerequisites
    1. Overview
    1. Callbacks in JavaScript
    1. Hitting HTTP Requests in JavaScript
    1. Callback Abstraction
    1. Closures
      Method Currying* 7. Promises
      Short-Hand Syntax for PromisesPromise ChainingFetch APIAsync-Await
 const puzzleAPIhit = () => {  
   const request = new XMLHttpRequest()  
   request.addEventListener('readystatechange', (e) => {  
     if (e.target.readyState === 4 && e.target.status === 200) {  
       const data = JSON.parse(e.target.responseText);  
       console.log(data.puzzle)  
     } else if (e.target.readyState === 4) {  
       console.log('An error has taken place')  
     }  
   })  
   request.open('GET', 'http://puzzle.mead.io/puzzle?wordCount=3')  
   request.send()  
 }  
 puzzleAPIhit();  

Now, when you open the “index.html” file in your browser, you can see a random string getting printed in the console.

Callback Abstraction

Now, what if we have a complex application that was built over this and thus the logic to generate a random string is something which we should keep hidden or abstract from “users.” To understand this, we can create three files:

    1. Prerequisites
    1. Overview
    1. Callbacks in JavaScript
    1. Hitting HTTP Requests in JavaScript
    1. Callback Abstraction
    1. Closures
      Method Currying* 7. Promises
      Short-Hand Syntax for PromisesPromise ChainingFetch APIAsync-Await
 <!DOCTYPE html>  
 <html>  
   <body>  
     <script src="makerequest.js"></script>  
     <script src="app.js"></script>  
   </body>  
 </html>  

    1. Prerequisites
    1. Overview
    1. Callbacks in JavaScript
    1. Hitting HTTP Requests in JavaScript
    1. Callback Abstraction
    1. Closures
      Method Currying* 7. Promises
      Short-Hand Syntax for PromisesPromise ChainingFetch APIAsync-Await
 const puzzleAPIhit = () => {  
   return 'some random string';  
 }  

    1. Prerequisites
    1. Overview
    1. Callbacks in JavaScript
    1. Hitting HTTP Requests in JavaScript
    1. Callback Abstraction
    1. Closures
      Method Currying* 7. Promises
      Short-Hand Syntax for PromisesPromise ChainingFetch APIAsync-Await
 const myPuzzle = puzzleAPIhit();  
 console.log(myPuzzle);  

Now, we need to replace the actual logic of finding the random string with the hardcoded return statement in thepuzzleAPIhit() function. But as the sending of an HTTP request is asynchronous innature, we can’t simply do this (changing the content of makerequest.js and keeping the other two files intact):

    1. Prerequisites
    1. Overview
    1. Callbacks in JavaScript
    1. Hitting HTTP Requests in JavaScript
    1. Callback Abstraction
    1. Closures
      Method Currying* 7. Promises
      Short-Hand Syntax for PromisesPromise ChainingFetch APIAsync-Await
 const puzzleAPIhit = () => {  
   const request = new XMLHttpRequest()  
   request.addEventListener('readystatechange', (e) => {  
     if (e.target.readyState === 4 && e.target.status === 200) {  
       const data = JSON.parse(e.target.responseText);  
       console.log(data.puzzle)  
       return data.puzzle;   
       /*  
         This is absolutely impossible the request.open() is   
         asynchronous in nature.  
       */  
     } else if (e.target.readyState === 4) {  
       console.log('An error has taken place')  
     }  
   })  
   request.open('GET', 'http://puzzle.mead.io/puzzle?wordCount=3')  
   request.send()  
 }  

Because in the console, it would be printing:

 undefined  
 Reliable Public Transportation //A random string  

This is happening because, as request.open()is asynchronous in nature, inside app.js, this is what happens:

    1. Prerequisites
    1. Overview
    1. Callbacks in JavaScript
    1. Hitting HTTP Requests in JavaScript
    1. Callback Abstraction
    1. Closures
      Method Currying* 7. Promises
      Short-Hand Syntax for PromisesPromise ChainingFetch APIAsync-Await
      The solution? Use callbacks. Here’s what we can do:
    1. Prerequisites
    1. Overview
    1. Callbacks in JavaScript
    1. Hitting HTTP Requests in JavaScript
    1. Callback Abstraction
    1. Closures
      Method Currying* 7. Promises
      Short-Hand Syntax for PromisesPromise ChainingFetch APIAsync-Await
 const myPuzzle = puzzleAPIhit((error, puzzle) => {  
   if(error) {  
     console.log(`Error: ${error}`)  
   } else {  
     console.log(puzzle)  
   }  
 });  


    1. Prerequisites
    1. Overview
    1. Callbacks in JavaScript
    1. Hitting HTTP Requests in JavaScript
    1. Callback Abstraction
    1. Closures
      Method Currying* 7. Promises
      Short-Hand Syntax for PromisesPromise ChainingFetch APIAsync-Await
 const puzzleAPIhit = (callback) => {  
   const request = new XMLHttpRequest()  
   request.addEventListener('readystatechange', (e) => {  
     if (e.target.readyState === 4 && e.target.status === 200) {  
       const data = JSON.parse(e.target.responseText)  
       callback(undefined, data.puzzle)  
     } else if (e.target.readyState === 4) {  
       callback('An error has taken place', undefined)  
     }  
   })  
   request.open('GET', 'http://puzzle.mead.io/puzzle?wordCount=3')  
   request.send()  
 }  

    1. Prerequisites
    1. Overview
    1. Callbacks in JavaScript
    1. Hitting HTTP Requests in JavaScript
    1. Callback Abstraction
    1. Closures
      Method Currying* 7. Promises
      Short-Hand Syntax for PromisesPromise ChainingFetch APIAsync-Await
      What have we done? We have just replaced the synchronous call with an asynchronous one by sending the callback in puzzleAPIhit() as an argument. And, in the method  puzzleAPIhit() itself, we called the callback after we got our results, which validates the basic definition of callbacks.
Closures

A closure is a function that has access to the variables defined in outer (and enclosing) functions. As far as scope is concerned, the closure has access to global variables, its own variables, and variables of outer (and enclosing) functions.

Consider the two simple examples of closures below:

 //////////////////////////Example 1://////////////////////////  
 const myFunction = () => {  
   const message = 'My New Message';  
   const printMessage = () => {  
     console.log(message);  
   }  
   printMessage();  
 }  
 myFunction();  
 //////////////////////////Example 2://////////////////////////  
 const myFunctionTwo = () => {  
   const message = 'My New Message Two';  
   const printMessage = () => {  
     console.log(message);  
   }  
   return printMessage;  
 }  
 const myPrintMessage = myFunctionTwo();  
 myPrintMessage();  


It produces the following output:

 My New Message  
 My New Message Two  

From example two, one can see that the closure has access to the message variable even after the function myFunctionTwo() completed its execution, and that’s the great advantage of using closures.

Method Currying

When a function, instead of taking all the arguments at once, takes only one argument and returns a function which will then take the rest of the arguments, this process is known as method currying.

For example:

 /*  
   We have a function adderFunction which returns another function.  
   That return function in turn returns the sum.  
  */  
 const adderFunction = (a) => {  
   return (b) => {  
     return a + b;  
   }  
 }  
 const addToTen = adderFunction(10);  
 console.log(addToTen(12));  
 console.log(addToTen(-1));  
 const addToThousand = adderFunction(1000);  
 console.log(addToTen(18));  
 console.log(addToTen(121));  

Which produces the following output:

 22  
 9  
 28  
 131  

As can be easily seen, now we don’t have to call the function each time with all its arguments, i.e, Method Currying helps in avoiding the need of passing a variable again and again. It also facilitates the reuse of our code.

Promises

Promises are a much more improvised approach of handling and structuring asynchronous code in comparison to doing the same with callbacks. To prove this we are going to compare and contrast promises with callbacks within the same code snippet. To simulate the delay, instead of calling a third-party API, we would be using the setTimeout() method just to make things a little simpler.

The Promise receives two callbacks in constructor function: resolve and reject. These callbacks inside promises provide us with fine-grained control over error handling and success cases. The resolve callback is used when the execution of promise performed successfully and the reject callback is used to handle the error cases.

When calling the promise, we have the method defined over the promise object which can be used to receive the data from promises accordingly.

Consider the following code snippet:

 //Example of Callback  
 const getDataCallback = (callback) => {  
   setTimeout(() => {  
     const temp = Math.floor(Math.random()*10 + 1);//Generates a random value [1, 10]  
     (temp <= 5)   
       ? callback(undefined, 'This is the Callback data')   
       : callback('This is the Callback error', undefined);    
   }, 10);  
 };  
 getDataCallback((error, data) => {  
   if(error) {  
     console.log(error);  
   } else {  
     console.log(data);  
   }  
 });  
 //Example of Promise  
 const myPromise = new Promise((resolve, reject) => {  
   setTimeout(() => {  
     const temp = Math.floor(Math.random()*10 + 1);//Generates a random value [1, 10]  
     (temp <= 5)   
       ? resolve('This is the Promise data')   
       : reject('This is the Promise error');    
   }, 10);  
 });  
 myPromise.then((data) => {  
   console.log(data);  
 }, (error) => {  
   console.log(error);  
 });  

It produces the following output:

 This is the Callback data  
 This is the Promise error  

Short-Hand Syntax for Promises

Suppose we have a function which accepts some integer and returns a promise based on some complex calculations (which, however, we will be simulating with setTimeout()). Actually, there is nothing special in Short-Hand Syntax except it provides a concise way of returning objects, variables or even promises from functions (functions using arrow syntax).

Consider the following code snippet:

 //Example of a function returning a Promise  
 const getDataFromPromise = (data) => {  
   return new Promise((resolve, reject) => {  
     setTimeout(() => {  
       (data <= 5)   
         ? resolve('This is the Promise data')   
         : reject('This is the Promise error');    
     }, 1000);  
   });  
 }    
 //Example of a function returning a Promise using Short-Hand syntax  
 const getDataFromPromiseUsingShortHandSyntax = (data) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (data <= 5)   
       ? resolve('This is the Promise data using Short-Hand syntax')   
       : reject('This is the Promise error using Short-Hand syntax');    
   }, 1000);  
 });  
 const myPromiseOne = getDataFromPromise(3);  
 myPromiseOne.then((data) => {  
   console.log(data);  
 }, (error) => {  
   console.log(error);  
 });  
 const myPromiseTwo = getDataFromPromiseUsingShortHandSyntax(30);  
 myPromiseTwo.then((data) => {  
   console.log(data);  
 }, (error) => {  
   console.log(error);  
 });  


It produces the following output:

 This is the Promise data  
 This is the Promise error using Short-Hand syntax  

Promise Chaining

Suppose we have a function, funcA(). Suppose funcA() returns a number after multiplying the input by 2; unless the input type is a number, it will return an error. And, based on the output received from funcA(), we again want to call the same function (i.e. functA()) by passing the output received from the first call as an input.

As we did before, while solving the problem above, we would be contrasting and comparing the callback approach and Promise approach.

Consider the following code snippet (callback approach):

 //Callback Approach  
 const funcA = (num, callback) => {  
   setTimeout(() => {  
     if(typeof num === 'number') {  
       callback(undefined, 2*num);  
     } else {  
       callback('Input type must be number');  
     }  
   }, 2000);  
 }  
 funcA(2, (error, data) => {  
   if(error) {  
     console.log(error);  
   } else {  
     funcA(data, (error, data) => {  
       if(error) {  
         console.log(error);  
       } else {  
         console.log('Final Output(Using Callback Approach): ' + data);  
       }  
     });  
   }  
 });  

As you can see, it is getting messier as it grows. What we’re seeing here is commonly called callback hell. Yes, there is actually a name for this messier code and, obviously, we need a better solution which is both manageable and understandable — Promise Chaining comes to our rescue here.

However, with Promises, we would be seeing two approaches here:

Consider the following code snippet (Promise approach, without Promise Chaining):

 const funcA = (num) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (typeof num === 'number')   
       ? resolve(2*num)   
       : reject('Input type must be number');  
   }, 2000);  
 });  
 funcA(2).then((data) => {  
   funcA(data).then((data) => {  
     console.log(data);  
   }, (error) => {  
     console.log(error);  
   });  
 }, (error) => {  
   console.log(error);  
 });  

Even without Promise Chaining, our code looks far leaner with the simple Promise approach as compared to the bare callback approach. Now, we would be looking a still better approach which uses Promise Chaining. Before moving to the code of Promise Chaining, let us put some light on it theoretically:

  1. When we return a Promise from another Promise handler (i.e. then()), it is called Promise Chaining.
  2. We can easily attach another then() handler when our Promise resolves (the one we have returned) and this can be done n number of times based on our needs.
  3. We can employ a single error handler called catch() which is attached at the very last of our Promise Chaining.

Consider the following code snippet (Promise approach, with Promise Chaining):

 const funcA = (num) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (typeof num === 'number')   
       ? resolve(12*num)   
       : reject('Input type must be number');  
   }, 2);  
 });  
 funcA(12).then((data) => {  
   return funcA(data);  
 }).then((data) => {  
   console.log(data);  
 }).catch((error) => {  
   console.log(error);  
 });  

As one can see, the code is much much cleaner and concise now, thanks to Promise Chaining.

Fetch API

The Fetch API was introduced in relatively newer versions of JavaScript and has built-in support for Promises. Technically, it is just another method of hitting HTTP Requests while harnessing the powers and perks of Promises and Promise Chaining.

So in the fetch API, you pass the arguments in the following order:

    1. Prerequisites
    1. Overview
    1. Callbacks in JavaScript
    1. Hitting HTTP Requests in JavaScript
    1. Callback Abstraction
    1. Closures
      Method Currying* 7. Promises
      Short-Hand Syntax for PromisesPromise ChainingFetch APIAsync-Await
      The fetch API simply returns a Promise and hence we can implement handlers to process the response from the Promise. Based on whether the Promise resolves or rejects, we can handle that with JavaScript’s then() method.

Consider the following code snippet:

 fetch('http://puzzle.mead.io/puzzle', {}).then((response) => {  
   if (response.ok) {  
     return response.json();  
     /*  
       Actually, the .json() method takes the response and returns a Promise Object and hence  
       We need to add another then() as we have done in Promise Chaining   
     */  
   } else {  
     throw new Error('Unable to fetch the puzzle');  
   }  
 }).then((data) => {  
   console.log(data.puzzle);  
 }).catch((error) => {  
   console.log(error);  
 });  

Suggested Reading: Mozilla-MDN-Fetch

Async-Await

We have the async function and the await operator. When we use them together we get a new way to structure and work with Promises that makes our code a whole lot easier to work with. So, what do async and await do? Let’s start with async:

Consider the following code snippet:

 const processData = () => {  
   return 12;  
 };  
 const processDataAsycn = async () => {  
   return 12;  
 };  
 console.log('Data from processData() without async: ' + processData() );  
 console.log('Data from processDataAsycn() with async: ' + processDataAsycn() );  

It produces the following output:

 Data from processData() without async: 12  
 Data from processDataAsycn() with async: [object Promise]  

As you can see, adding the async keyword to a function makes it work a bit differently. It starts returning a promise. The promise we get back from an async function gets resolved with whatever value we return from that function. As with any function returning promises, we can handle the response (i.e. promise) from an async function using handlers like catch and then.

Consider the following code snippet:

 const processDataAsycn = async (num) => {  
   if(typeof num === 'number') {  
     return 2*num;  
   } else {  
     throw new Error('Something went wrong');  
   }  
 };  
 processDataAsycn(21).then((data) => {  
   console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data);  
 }).catch((error) => {  
   console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error);  
 });  

Now, moving to the await operator, let us suppose we have an async function, processData(), that calls a function, getDataPromise(), which, in turn, returns a promise. Now, we want to parse/use the returned data. Let’s look at how we would solve the problem without the await operator.

Consider the following code snippet:

 const getDataPromise = (num) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (typeof num === 'number') ? resolve(num * 2) : reject('Input must be an number');  
   }, 2000);  
 });  
 const processDataAsycn = async () => {  
   return getDataPromise(22).then((data) => {  
     return getDataPromise(data);  
   });  
 };  
 processDataAsycn().then((data) => {  
   console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data);  
 }).catch((error) => {  
   console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error);  
 });   

Now, we’re implementing the same logic with the await keyword so that we can compare and contrast the two methods. Actually, the await keyword makes JavaScript wait until that promise settles and returns its result. So, it looks like the code is synchronous but it is indeed asynchronous.

Consider the following code snippet:

 const getDataPromise = (num) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (typeof num === 'number') ? resolve(num * 2) : reject('Input must be an number');  
   }, 2000);  
 });  
 const processDataAsycn = async () => {  
   let data = await getDataPromise(2);  
   data = await getDataPromise(data);  
   return data;  
 };  
 processDataAsycn().then((data) => {  
   console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data);  
 }).catch((error) => {  
   console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error);  
 });   

So with async and await operator, we can structure our code that uses promises to look more like regular old synchronous code. We can perform one operation after the other. This code is never going to run until the previous promise either resolves or rejects the return statement.

Now, in this case, we’ve only seen the happy path where all of the promises do indeed resolve. Let’s go ahead and explore what happens when one of them is rejected.

Consider the following code snippet:

 const getDataPromise = (num) => new Promise((resolve, reject) => {  
   setTimeout(() => {  
     (typeof num === 'number') ? resolve(num * 2) : reject('Input must be an number');  
   }, 2000);  
 });  
 const processDataAsycn = async () => {  
   let data = await getDataPromise('2');  
   data = await getDataPromise(data);  
   return data;  
 };  
 processDataAsycn().then((data) => {  
   console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data);  
 }).catch((error) => {  
   console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error);  
 });   

It produces the following output:

 Error from processDataAsycn() with async( When promise gets rejected ): Input must be an number  

The awake operator throws the error for us if the promise is rejected. We can see that promise chaining is no longer a daunting thing.

Feel free to leave any comment or questions. Thanks!

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!