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.

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 Phelps. *Similarly 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 it. **Our 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

What is GEEK

Buddha Community

A guide to this in JavaScript

Randy Rickards

1548833558

good

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Hire Dedicated JavaScript Developers -Hire JavaScript Developers

It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.

Does your business need an interactive website or app?

Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.

The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.

Get your business app with JavaScript

For more inquiry click here https://bit.ly/31eZyDZ

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers

Niraj Kafle

1589255577

The essential JavaScript concepts that you should understand

As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.

#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips

Cayla  Erdman

Cayla Erdman

1597470780

A quick guide to JavaScript Arrays

Introduction

Arrays are a structure common to all programming languages so knowing what they are and having a firm grasp on what you’re able to accomplish with Arrays will take you a long way in your journey as a software developer. The code examples I share in this post will be in JavaScript but the concepts are common among all languages. What you learn here can easily be translated to any other language you work with.

In this post I’ll be covering how to perform the create, read update and delete operations using arrays, some common functions that come with the Array prototype and also how to implement them.


What is an Array

Before we jump into the juicy bits of Arrays, lets quickly gloss over what they are. Arrays

  • are a fundamental data type in JavaScript
  • are an ordered collection of values called **elements **that are stored at and accessed via an index
  • are untyped, meaning that the elements of an array could be of different types. This allows us to create complex arrays such as an array of objects or even an array of arrays (multidimensional arrays)
  • can have elements that are constants or expressions
  • have a property called length that tells you the number of elements in the array
  • inherit properties from Array.prototype that includes a wide variety useful functions that can be called from arrays or array-like objects

CRUD operations using Arrays

If you’re not familiar with the term CRUD it stands for Create, Read, Update and Delete. In this section we’ll go through each one of these operations and cover different ways you can perform each one.

Creating Arrays

There are several ways you can create an Array but the most common ways are by using

  • the Array literal syntax
  • the Array constructor i.e. new Array()

Lets take a look at each one with examples

Array literal

The array literal is the most common way of creating an array. It uses the square brackets as a notion of a container followed by comma separated values inside the square brackets. The following examples show how to use the array literal syntax and how arrays are untyped i.e. can contain elements of different types.

Image for post

Examples of untyped arrays in JavaScript created with the array literal syntax.

Array constructor

Another way to create an array is through the Array constructor.

const myArray = new Array();

Using the Array constructor, as shown above, is the same as creating an array with the array literal syntax. i.e.

// The following two lines behave exactly the same way i.e. both create an empty arrays

const myArray = new Array();
const myOtherArray = [];

The array constructor, however, is able to receive arguments that allow it to behave in different ways depending on the number and type of arguments passed to it.

  • You can pass a single numeric argument which creates an array of the specified length. This option is mostly used when you know how many elements you’ll be placing in the array
const myArray = new Array(5);

Note: If you want to define the array with a specified size, as shown above, the argument passed must be a numeric value. Any other type would be considered as the first element that’ll be placed in the array.

  • Or you can pass two or more arguments or a non-numeric argument to place the values inside the array. This works the same way as shown in the array literal examples.

Image for post

Examples of arrays created by using the Array constructor in JavaScript

As stated earlier, these two ways are the most common ways of creating arrays that you’ll see and use 99% of the time. There are a few other ways but we won’t dive deep into how they work. They are

  • the spread operator const someArray = […someOtherArray]
  • the static method Array.of()
  • and the static method Array.from()

#javascript #web-development #javascript-tips #javascript-development #javascript-arrays #sql

Ajay Kapoor

1626321063

JS Development Company India | JavaScript Development Services

PixelCrayons: Our JavaScript web development service offers you a feature-packed & dynamic web application that effectively caters to your business challenges and provide you the best RoI. Our JavaScript web development company works on all major frameworks & libraries like Angular, React, Nodejs, Vue.js, to name a few.

With 15+ years of domain expertise, we have successfully delivered 13800+ projects and have successfully garnered 6800+ happy customers with 97%+ client retention rate.

Looking for professional JavaScript web app development services? We provide custom JavaScript development services applying latest version frameworks and libraries to propel businesses to the next level. Our well-defined and manageable JS development processes are balanced between cost, time and quality along with clear communication.

Our JavaScript development companies offers you strict NDA, 100% money back guarantee and agile/DevOps approach.

#javascript development company #javascript development services #javascript web development #javascript development #javascript web development services #javascript web development company