0
0
Javascriptprogramming~20 mins

this in objects in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Master of this in Objects
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this code?
Consider the following JavaScript code. What will be logged to the console?
Javascript
const obj = {
  value: 42,
  getValue: function() {
    return this.value;
  }
};
console.log(obj.getValue());
A42
Bundefined
CTypeError
Dnull
Attempts:
2 left
💡 Hint
Remember, inside a method, 'this' refers to the object before the dot.
Predict Output
intermediate
2:00remaining
What does this code output?
Look at this code snippet. What will it print?
Javascript
const obj = {
  value: 10,
  getValue: () => this.value
};
console.log(obj.getValue());
A10
Bundefined
CTypeError
D0
Attempts:
2 left
💡 Hint
Arrow functions do not have their own 'this'.
Predict Output
advanced
2:00remaining
What is the output of this code?
What will this code print to the console?
Javascript
const obj = {
  value: 5,
  getValue: function() {
    const inner = function() {
      return this.value;
    };
    return inner();
  }
};
console.log(obj.getValue());
Aundefined
B5
CTypeError
DReferenceError
Attempts:
2 left
💡 Hint
Regular functions have their own 'this' depending on how they are called.
Predict Output
advanced
2:00remaining
What will this code output?
Analyze the following code and select the correct output.
Javascript
const obj = {
  value: 7,
  getValue: function() {
    const inner = () => this.value;
    return inner();
  }
};
console.log(obj.getValue());
Aundefined
Bnull
CTypeError
D7
Attempts:
2 left
💡 Hint
Arrow functions inherit 'this' from their surrounding context.
🧠 Conceptual
expert
2:00remaining
Which option causes a TypeError when accessing 'this.value'?
Which of the following code snippets will cause a TypeError when trying to access 'this.value'?
A
const obj = { value: 1 };
const getValue = obj.getValue;
getValue();
B
const obj = { value: 1, getValue() { return this.value; } };
const getValue = obj.getValue.bind(obj);
getValue();
C
const obj = { value: 1, getValue() { return this.value; } };
const getValue = obj.getValue.bind(null);
getValue();
D
const obj = { value: 1, getValue() { return this.value; } };
obj.getValue();
Attempts:
2 left
💡 Hint
Binding 'this' to null in strict mode can cause errors.