Skip to main content

Explained Simply: “This” Keyword in JavaScript

 

“This” in any programming language is a strange concept to understand due to the ambiguity of the definition.

Simply put, because This is used in many different ways it is difficult to precisely define. The best way to learn this is to learn the many different ways in which this can change.

  1. Start with a simple console.log(this);

By a simple console.log, you can quickly tell gain understanding into what this is. \

console.log(this);

The This keyword is pointing to the global object. “This” is the “world” or the context of which this resides. Whenever you see the curly brackets {} in programming, that means the code residing in a different context. Without curly braces and logging console.log in the open, “This” is simply the global object. For a simple explanation of context, please check out my Youtube video.

2. Next, console.log(this) within a function

function show() {
   console.log(this === window); // true
}

show();

This is a tricky topic inside of functions (no pun intended). When functions are executed in the global scope, the value of this is the window object.

The above function was not executed inside of any other function or object, so by default show was called on the global object.

3. Next, console.log(this) within an object

let person = {
    name: "teddy",
    getName: function() {
        return this.name;
    }
}

console.log(person.getName()) // teddy

In the above example, the “this” object in getName references the person object.

let me = person.getname;
console.log(me()); // undefined

You get undefined instead of “teddy” because when you call a method without specifying its object, Javascript sets “this” to the global object.

let person = {
      name: 'teddy',
      getName: function() {
            return this.name;
      }
}

let teddy = {
      shirt: 'the eagles'
}

let shirt = person.getName.bind(teddy);

console.log(shirt());

4. Lastly, console.log(this) inside an arrow function.

ES6 introduced a new concept called the arrow function. In arrow functions, JavaScript sets the “this” lexically.

This means the arrow function does not create its own execution context, but inherits the “this” from the outer function.

let thisArrowFunction = () => this;
console.log(thisArrowFunction() === window); //true

In this example, there is no outer function so the execution content is the global object.

Comments

Popular posts from this blog

Higher Order Functions in JavaScript Explained Simply

  What is a higher order function? In JavaScript, a higher-order function is a function that  takes one or more functions as arguments,  or returns a function as output. These functions are a powerful feature of the language that allow you to write concise and expressive code. The best way to learn higher order functions (and likely the most “real-world”) is to look at “map()” and “filter()”. Both take functions as arguments where the function is applied to each element in an array. Map For example, consider the  map  function, which is used to apply a function to each element of an array and return a new array containing the results. The  map   function is a higher-order function because it takes a function as its argumen t, in this case the function to apply to each element of the array. const numbers = [1, 2, 3, 4, 5]; const squares = numbers.map(x => x * x); Filter Another common higher-order function is  filter , which is used to select el...

Basic CRUD Array Operations in JavaScript

  Sometimes it pays just to stick to the basics. Here are CRUD operations for a basic array: 1. Create an element to the end of an array let clubs = ['baseball','running','computer club']; clubs.push('tennis'); console.log(clubs); 2. Delete an element from the end of an array let clubs = ['baseball','running','computer club']; const lastElement = seas.pop(); console.log(lastElement); 3. Reading an index from an element in an array let clubs = ['baseball','running','computer club']; let index = clubs.indexOf("running"); console.log(index); 4. Update an index from an element in an array let clubs = ['baseball','running','computer club']; clubs.splice(1, 0, 'tennis'); console.log(clubs);

Immutability in JavaScript

  Immutability is a popular concept not just in JavaScript, but most programming languages in general. The reason behind this of course is functional programming which gives software developers a brand new paradigm to utilize when coding. Let’s dive into the details of mutability and immutability. What is Mutability? A mutable value is one that can be changed without creating an entirely new value.   In JavaScript, objects and arrays are mutable by default, but primitive values are not.  Once a primitive value is created, it cannot be changed, although the variable that holds it may be reassigned. There is nothing wrong with mutability. Take a look at the code below: const dog = { name: 'turtle', age: 10 } // Make a copy of dog object const newDog = dog; // Changing the age of the new dog newDog.age = 12; console.log(newDog === dog); // true As you can see, we’re copying the object to another object and changing the dogs age. The problem is that the change happe...