Challenge - 5 Problems
Master of this in Objects
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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());
Attempts:
2 left
💡 Hint
Remember, inside a method, 'this' refers to the object before the dot.
✗ Incorrect
The method getValue is called on obj, so 'this' inside getValue refers to obj. obj.value is 42, so 42 is returned and logged.
❓ Predict Output
intermediate2: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());
Attempts:
2 left
💡 Hint
Arrow functions do not have their own 'this'.
✗ Incorrect
Arrow functions inherit 'this' from their surrounding scope, which is the global scope here. Since 'value' is not defined globally, it returns undefined.
❓ Predict Output
advanced2: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());
Attempts:
2 left
💡 Hint
Regular functions have their own 'this' depending on how they are called.
✗ Incorrect
The inner function is called without an object, so 'this' inside inner refers to the global object (or undefined in strict mode). Since global.value is undefined, the result is undefined.
❓ Predict Output
advanced2: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());
Attempts:
2 left
💡 Hint
Arrow functions inherit 'this' from their surrounding context.
✗ Incorrect
The arrow function inner inherits 'this' from getValue, which is called on obj. So 'this.value' is 7.
🧠 Conceptual
expert2: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'?
Attempts:
2 left
💡 Hint
Binding 'this' to null in strict mode can cause errors.
✗ Incorrect
Binding 'this' to null means inside getValue, 'this' is null. Accessing 'this.value' causes a TypeError because you can't read properties of null.