0
0
Javascriptprogramming~20 mins

What this keyword represents in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Master of this keyword
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of this in a regular function
What is the output of the following code when calling obj.show()?
Javascript
const obj = {
  name: 'Alice',
  show: function() {
    console.log(this.name);
  }
};
obj.show();
A"Alice"
Bundefined
CReferenceError
D"obj"
Attempts:
2 left
💡 Hint
Inside an object method, this refers to the object itself.
Predict Output
intermediate
2:00remaining
Value of this in arrow function inside object
What will be logged when calling obj.show() in this code?
Javascript
const obj = {
  name: 'Bob',
  show: () => {
    console.log(this.name);
  }
};
obj.show();
A"obj"
B"Bob"
Cundefined
DReferenceError
Attempts:
2 left
💡 Hint
Arrow functions do not have their own this.
Predict Output
advanced
2:00remaining
this inside event listener function
What does this refer to inside the event listener function in this code?
Javascript
const button = document.createElement('button');
button.textContent = 'Click me';
document.body.appendChild(button);

button.addEventListener('click', function() {
  console.log(this);
});
AThe button element that was clicked
BThe global window object
Cundefined
DThe document object
Attempts:
2 left
💡 Hint
In event listeners, this refers to the element the listener is attached to.
Predict Output
advanced
2:00remaining
this in class method with setTimeout
What will be logged when calling obj.delayedShow()?
Javascript
class Person {
  constructor(name) {
    this.name = name;
  }
  delayedShow() {
    setTimeout(function() {
      console.log(this.name);
    }, 100);
  }
}
const obj = new Person('Carol');
obj.delayedShow();
AReferenceError
Bundefined
C"Carol"
DTypeError
Attempts:
2 left
💡 Hint
Regular functions inside setTimeout have this as the global object or undefined in strict mode.
🧠 Conceptual
expert
2:00remaining
Understanding this binding with call, apply, and bind
Given the code below, which option correctly shows the output of greet.call(person, 'Hello')?
Javascript
function greet(greeting) {
  return `${greeting}, my name is ${this.name}`;
}
const person = { name: 'Dave' };
ATypeError
B"Hello, my name is greet"
C"Hello, my name is undefined"
D"Hello, my name is Dave"
Attempts:
2 left
💡 Hint
call sets this explicitly to the first argument.