Interview Question - JavaScript this - Calling Output

This is an interview question on JavaScript this keyword.


var obj = {
property: 21,
f: function() {

Full Transcript

00:00 In this question, we have created an object called obj. This object has one property called property and one method called f. The implementation of f returns the value of to the caller. In the last line, we are calling method f on obj and logging the result on the console. Let's work together to find the right answer. So here we're invoking the method on object obj, which invokes this function. Now how do we know the value of this in the method implementation? To do that, we must identify how f was called and not how it was declared. So as we see, f was invoked as a method called on object obj. Therefore obj becomes the value of this. So when looking for, we will look for the property and obj which has the value of 21 which is the correct answer for this question.

00:53 Let's run this in the editor to make sure our understanding is correct. As it run this code in the editor, we can confirm that the value of 21 is indeed correct. And that's it. If you work with JavaScript or any other frameworks such as jQuery, angular, or react, you have executed JavaScript on the browser. So the new course that we have launched is relevant for you. It's called Browser JavaScript and event loop. This goes educates on how JavaScript is executed behind the scenes, and we'll cover various topics such as ExecutionContext and event loop. You will have the opportunity to visually see every step of JavaScript code execution. Check out the course link in the description below to learn more about the course and let us know if you have any questions. Keep learning and see you next time.