A guide to this in JavaScript

The this keyword hands-down is one of the most widely used and yet misunderstood in JavaScript. I’ll try to change that today.

The this keyword hands-down is one of the most widely used and yet misunderstood in JavaScript. I’ll try to change that today.

Let’s go back to the good old school days, when we learned about pronouns.

Phelps is swimming fast because he wants to win the race.

Note the use of the pronoun “he”. We don’t directly address Phelps here but use the pronoun he to refer to PhelpsSimilarly JavaScript uses the thiskeyword as a referent to refer to the object in context i.e the subject.

Example:

var car= {
make: "Lamborghini",
model: "Huracán",
fullName: function () {
console.log(this.make+" " +this.model);
console.log(car.make+ " " +car.model);
}
}
car.fullName();

In the above code, we have an object car which has the properties make, model and fullName. The value of fullName is a function which prints the full name of the car using 2 different syntaxes.

  • Using this => this.make+” “ +this.model the this refers to the object in context which is car so this.make is effectively car.make and so is this.model .
  • Using dot notation, we can access the properties of objects, car.make & car.model .

this is it!

Now that we have understood what is this and it’s most basic usage, let’s make some rules of thumb so we can always remember.

The JS this keyword refers to the object it belongs to.

var car={
make:'....'
func:()=>{console.log(this.make)}}

The this in the above snippet belongs to the object car.

It takes different values depending upon the usage

  1. Inside a method.
  2. Inside a function.
  3. Alone.
  4. In an event.
  5. call(), and apply().

Inside a method

When this is used inside a method, it refers to the owner object.

Functions defined inside an object are called methods. Let’s take our car example again.

var car= {
make: "Lamborghini",
model: "Huracán",
fullName: function () {
console.log(this.make+" " +this.model);
console.log(car.make+ " " +car.model);
}
}
car.fullName();

fullName() here is a method. The this inside this method belongs to car.

Inside a function

this inside a function is a bit complicated. First thing to understand is that, like all objects have properties, likewise functions have properties too. Whenever that function is executed, it gets the this property, which is a variable with the value of the object that invokes it.

this is really just a shortcut reference for the “antecedent object” — the invoking object. — javascriptissexy.com

If the function is not invoked by an object then the this inside the function belongs to the global object, which is called window. In this case this will refer to the values defined in the global scope. Let’s see an example for better understanding:

var make= "Mclaren";
var model= "720s"
function fullName(){ 
console.log(this.make+ " " + this.model);
}
var car = {
 make:"Lamborghini",
 model:"Huracán",
 fullName:function () {
 console.log (this.make + " " + this.model);
 }
}
 car.fullName(); // Lmborghini Huracán
    window.fullName(); // Mclaren 720S
    fullName(); // Mclaren 720S

Here make, model and fullName are defined globally, while car object has an implementation of fullName as well. When invoked by the car object this referred to the properties defined inside the object. On the other hand, the other two function callings are the same and return the globally defined properties.

Alone

When used alone not inside any function or object, this refers to the global object.

The this here refers to the global name property.

In an event

Events can be of any type, but for the sake of simplicity and clarity, let’s take a click event.

Whenever a button is clicked and an event is raised, it can call another function to do a certain task based on the click. If this is used inside that function, it will refer to the element which raised the event. In the DOM, all the elements are stored as objects. That is why when an event is raised it refers to that element, because that webpage element is actually an object inside the DOM.

Example:

<button onclick="this.style.display='none'">
  Remove Me!
</button>

call(), apply() & bind()

  • bind: allows us to set the this value on methods.
  • call & apply: allow us to borrow functions and set the this value on function invocation.

Call, Bind and Apply are in themselves a topic of another post. They are very important, and explaining them here is not possible as we should know all about this to know the usage of these functions.

The trickiest part

If understood well, this make our work easier in a way. But there are some cases where it is misunderstood.


Example 1.

var car = {
make:"Lamborghini",
model:"Huracán",
name:null,
fullName:function () {
this.name=this.make + " " + this.model;
console.log (this.name);
}
}
var anotherCar={
make:"Ferrari",
model:"Italia",
name:null}
 anotherCar.name= car.fullName();

We get an unexpected result here. We borrowed a method that uses thisfrom another object, but the problem here is that the method is only assigned to anotherCar function but is actually invoked on car object. That’s why we get the result as Lamborghini and not Ferrari.

To resolve this, we use the call() method.

Here the call() method calls fullName() on anotherCar object which originally does not have the fullName() function.

We can also see that, when we log the car.name and anotherCar.name we get the result for the latter not on former, which means that the function was indeed invoked on anotherCar and not on car.

Example 2.

var cars=[
{ make: "Mclaren", model: "720s"},{make: "Ferrari",model: "Italia"}]
var car = {cars:[{make:"Lamborghini", model:"Huracán"}],
fullName:function () {console.log(this.cars[0].make + " " + this.cars[0].model);}}
var vehicle=car.fullName;
vehicle()

In the above snippet we have a global object called cars and we have the same name object inside the car object. The fullName() method is then assigned to the vehicle variable which is then called. The variable belongs to the global object so this calls the global cars object instead of the cars object because of the context.

To resolve that we use .bind() function to solve the issue.

Binding helps us with specifically setting the this value and hence the vehicle variable explicitly points to the car object and not the global object, so this lies in the context of the car object.

Example 3.

var car = {
cars:[{make:"Lamborghini",model:"Huracán"},
{ make: "Mclaren", model: "720s"},
{make: "Ferrari",model: "Italia"}],
fullName:function(){this.cars.forEach(()=>{console.log (this.make + " " + this.model);
})}}
car.fullName();

In the above snippet, the fullName() calls upon a function which iterated through the cars array using forEach. Inside the forEach there is an anonymous function where this loses context. A function inside a function in JavaScript is called a closure. Closures are very important and widely used in JavaScript.

Another important concept playing a role here is scope. A variable inside a function cannot access variables and properties outside its scope. thisinside the anon function cannot access this outside it. So this has nowhere to go but to point to global object. But there, no property is defined for thisto access so undefined is printed.

A workaround for the above is that we can assign a variable the value of this, outside the anonymous function and then use it inside it.

Here, the self variable contains the value of this which is used with the inner function thus giving us the output.

Example 4.

var car= {
make: "Lamborghini",
model: "Huracán",
fullName: function (cars) {
cars.forEach(function(vehicle){
console.log(vehicle +" "+ this.model);
})}}
car.fullName(['lambo','ferrari','porsche']);

This is a revisited example, in which this wasn't accessible so we preserved it's value by using a variable called self. Let's use arrow function to solve the same:

As you can see, using an arrow function in forEach() automatically solves the problem and we don’t have to do bind, or give the this value to some other variable. This is because arrow functions bind their context so thisactually refers to the originating context, or the originating object.

Example 5.

var car= {
make: "Lamborghini",
model: "Huracán",
fullName: function () {
console.log(this.make +" "+ this.model);
}}
var truck= {
make: "Tesla",
model: "Truck",
fullName: function (callback) {
console.log(this.make +" "+ this.model);
callback();
}}
truck.fullName(car.fullName);

The above code consists of two identical objects, with one containing a callback function. A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine.

Here, the truck object’s fullName method consists of a callback which is also invoked inside itOur car object is as before. When we invoke the truck’s fullName method with the callback(argument) as the fullName method of the car object, we get output as Tesla Truck and undefined undefined.

After reading about this some of you might have gotten a hunch that car.fullName would print the model and make of the truck object, but to your disappointment, this again played a trick on us. Here the car.fullNameis passed as an argument and is not actually invoked by the truck object. The callback invokes the car object method, but note that the actual call site for the function is the callback which binds this to the global object. It's a bit confusing, so read it again!

Here to get clarity, we print this itself. We can see that the this of callback is given a global scope. So to get a result we create global make and modelproperties.

Again, running the same code with global make and model properties we finally get the answer to the global this. This proves that this references the global object.

To get the results which we desire, the car.fullName result we will again use bind() to hard-bind the car object to the callback, which will make everything right again.

Solved!

No doubt that this is very useful, but has it's own pitfalls too. Hope I made it quite easy for you to understand. If you want more content simplified like this, follow me on Medium. Please leave your responses and share this if you liked it.


By : ashay mandwarya





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!