Tuesday, August 27, 2019

The JavaScript this Keyword

Example

var person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};
Try it Yourself »

What is this?

The JavaScript this keyword refers to the object it belongs to.
It has different values depending on where it is used:
  • In a method, this refers to the owner object.
  • Alone, this refers to the global object.
  • In a function, this refers to the global object.
  • In a function, in strict mode, this is undefined.
  • In an event, this refers to the element that received the event.
  • Methods like call(), and apply() can refer this to any object.

this in a Method

In an object method, this refers to the "owner" of the method.
In the example on the top of this page, this refers to the person object.
The person object is the owner of the fullName method.
fullName : function() {
  return this.firstName + " " + this.lastName;
}
Try it Yourself »

this Alone

When used alone, the owner is the Global object, so this refers to the Global object.
In a browser window the Global object is [object Window]:

Example

var x = this;
Try it Yourself »
 In strict mode, when used alone, this also refers to the Global object [object Window]:

Example

"use strict";
var x = this;
Try it Yourself »

this in a Function (Default)

In a JavaScript function, the owner of the function is the default binding for this.
So, in a function, this refers to the Global object [object Window].

Example

function myFunction() {
  return this;
}
Try it Yourself »

this in a Function (Strict)

JavaScript strict mode does not allow default binding.
So, when used in a function, in strict mode, this is undefined.

Example

"use strict";
function myFunction() {
  return this;
}
Try it Yourself »

this in Event Handlers

In HTML event handlers, this refers to the HTML element that received the event:

Example

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

Object Method Binding

In these examples, this is the person object (The person object is the "owner" of the function):

Example

var person = {
  firstName  : "John",
  lastName   : "Doe",
  id         : 5566,
  myFunction : function() {
    return this;
  }
};
Try it Yourself »

Example

var person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};
Try it Yourself »
In other words: this.firstName means the firstName property of this (person) object.

Explicit Function Binding

The call() and apply() methods are predefined JavaScript methods.
They can both be used to call an object method with another object as argument.
You can read more about call() and apply() later in this tutorial.
In the example below, when calling person1.fullName with person2 as argument, this will refer to person2, even if it is a method of person1:

Example

var person1 = {
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}
var person2 = {
  firstName:"John",
  lastName: "Doe",
}
person1.fullName.call(person2);  // Will return "John Doe"

JavaScript Hoisting

Hoisting is JavaScript's default behavior of moving declarations to the top.

JavaScript Declarations are Hoisted

In JavaScript, a variable can be declared after it has been used.
In other words; a variable can be used before it has been declared.
Example 1 gives the same result as Example 2:

Example 1

x = 5// Assign 5 to x
elem = document.getElementById("demo"); // Find an element elem.innerHTML = x;                     // Display x in the element
var x; // Declare x
Try it Yourself »

Example 2

var x; // Declare xx = 5// Assign 5 to x
elem = document.getElementById("demo"); // Find an element elem.innerHTML = x;                     // Display x in the element
Try it Yourself »
To understand this, you have to understand the term "hoisting".
Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

The let and const Keywords

Variables and constants declared with let or const are not hoisted!
Read more about let and const in JS Let / Const.


JavaScript Initializations are Not Hoisted

JavaScript only hoists declarations, not initializations.
Example 1 does not give the same result as Example 2:

Example 1

var x = 5// Initialize xvar y = 7// Initialize y
elem = document.getElementById("demo"); // Find an element elem.innerHTML = x + " " + y;           // Display x and y
Try it Yourself »

Example 2

var x = 5// Initialize x
elem = document.getElementById("demo"); // Find an element elem.innerHTML = x + " " + y;           // Display x and y
var y = 7// Initialize y
Try it Yourself »
Does it make sense that y is undefined in the last example?
This is because only the declaration (var y), not the initialization (=7) is hoisted to the top.
Because of hoisting, y has been declared before it is used, but because initializations are not hoisted, the value of y is undefined.
Example 2 is the same as writing:

Example

var x = 5// Initialize xvar y;     // Declare y
elem = document.getElementById("demo"); // Find an element elem.innerHTML = x + " " + y;           // Display x and y
y = 7;    // Assign 7 to y
Try it Yourself »

Declare Your Variables At the Top !

Hoisting is (to many developers) an unknown or overlooked behavior of JavaScript.
If a developer doesn't understand hoisting, programs may contain bugs (errors).
To avoid bugs, always declare all variables at the beginning of every scope.
Since this is how JavaScript interprets the code, it is always a good rule.
JavaScript in strict mode does not allow variables to be used if they are not declared.
Study "use strict" in the next chapter.

JavaScript Const

ECMAScript 2015

ES2015 introduced two important new JavaScript keywords: let and const.
Variables defined with const behave like let variables, except they cannot be reassigned:

Example

const PI = 3.141592653589793;
PI = 3.14;      // This will give an errorPI = PI + 10;   // This will also give an error
Try it Yourself »

Block Scope

Declaring a variable with const is similar to let when it comes to Block Scope.
The x declared in the block, in this example, is not the same as the x declared outside the block:

Example

var x = 10;
// Here x is 10
  const x = 2;
  // Here x is 2}
// Here x is 10
Try it Yourself »
You can learn more about Block Scope in the previous chapter: JavaScript Let.

Assigned when Declared

JavaScript const variables must be assigned a value when they are declared:

Incorrect

const PI;
PI = 3.14159265359;

Correct

const PI = 3.14159265359;

Not Real Constants

The keyword const is a little misleading.
It does NOT define a constant value. It defines a constant reference to a value.
Because of this, we cannot change constant primitive values, but we can change the properties of constant objects.

Primitive Values

If we assign a primitive value to a constant, we cannot change the primitive value: 

Example

const PI = 3.141592653589793;
PI = 3.14;      // This will give an errorPI = PI + 10;   // This will also give an error
Try it Yourself »

Constant Objects can Change

You can change the properties of a constant object:

Example

// You can create a const object:const car = {type:"Fiat", model:"500", color:"white"};

// You can change a property:car.color = "red";

// You can add a property:car.owner = "Johnson";
Try it Yourself »
But you can NOT reassign a constant object:

Example

const car = {type:"Fiat", model:"500", color:"white"};
car = {type:"Volvo", model:"EX60", color:"red"};    // ERROR
Try it Yourself »

Constant Arrays can Change

You can change the elements of a constant array:

Example

// You can create a constant array:const cars = ["Saab""Volvo""BMW"];

// You can change an element:cars[0] = "Toyota";

// You can add an element:cars.push("Audi");
Try it Yourself »
But you can NOT reassign a constant array:

Example

const cars = ["Saab""Volvo""BMW"];
cars = ["Toyota""Volvo""Audi"];    // ERROR
Try it Yourself »

Browser Support

The const keyword is not supported in Internet Explorer 10 or earlier.
The following table defines the first browser versions with full support for the const keyword:
Chrome 49IE / Edge 11Firefox 36Safari 10Opera 36
Mar, 2016Oct, 2013Feb, 2015Sep, 2016Mar, 2016


Redeclaring

Redeclaring a JavaScript var variable is allowed anywhere in a program:

Example

var x = 2;    //  Allowedvar x = 3;    //  Allowedx = 4;        //  Allowed
Redeclaring or reassigning an existing var or let variable to const, in the same scope, or in the same block, is not allowed:

Example

var x = 2;         // Allowedconst x = 2;       // Not allowed{
  let x = 2;     // Allowed  const x = 2;   // Not allowed}
Redeclaring or reassigning an existing const variable, in the same scope, or in the same block, is not allowed:

Example

const x = 2;       // Allowedconst x = 3;       // Not allowedx = 3;             // Not allowedvar x = 3;         // Not allowedlet x = 3;         // Not allowed
{
  const x = 2;   // Allowed  const x = 3;   // Not allowed  x = 3;         // Not allowed  var x = 3;     // Not allowed  let x = 3;     // Not allowed}
Redeclaring a variable with const, in another scope, or in another block, is allowed:

Example

const x = 2;       // Allowed
{
  const x = 3;   // Allowed}

{
  const x = 4;   // Allowed}

Hoisting

Variables defined with var are hoisted to the top (if you don't know what Hoisting is, read our Hoisting Chapter).
You can use a var variable before it is declared:

Example

carName = "Volvo";    // You CAN use carName herevar carName;
Try it Yourself »
Variables defined with const are not hoisted to the top.
const variable cannot be used before it is declared:

Example

carName = "Volvo";    // You can NOT use carName hereconst carName = "Volvo";