r/learnjavascript • u/OrangeObvious8498 • Feb 17 '26
this keyword learning
this keyword in javascript is very confusing especially during interviews. Everytime, its very confusing to understand and easily to forget.
What would be the best resource to learn this?
4
Upvotes
View all comments
Show parent comment
3
u/delventhalz Feb 17 '26 edited Feb 18 '26
Building off of this answer, I think the clearest description of
thisis just this is the thing to the left of the dot when you call a method... except when it isn't.The "except when it isn't" part is a list of exceptions that don't really have much rhyme or reason to them, but the list is not too long and is mostly made up of weird edge cases you can ignore. Here they are in order of importance:
1. When using the new keyword to call a constructor, this is the new object
In a function called in "constructor mode" (i.e. after the keyword
new),thiswill refer to the new object being constructed.2. When in an arrow function, this comes from the surrounding scope
Arrow functions have no
this. Like any other variable that doesn't exist in a nested scope, variable lookup will fallback to the wrapping scope. So you will get thethisof whatever scope is surrounding the arrow function.3. When not in a function, the value of this depends...
Probably shouldn't reference
thisoutside of a function, but if you do, its value varies depending on the exact context of how your code is run. In the browser, it is commonly thewindowobject (both in the console and in vanilla JS files), but if you are running browser code from an ES module, it will beundefined. In the Node console it will beglobalobject (similar towindow), but when you use Node to run a JS file,thiswill either beundefined(if run from an ES module), or theexportsobject (if run from a CJS module).EDIT: Thanks to /u/senocular for correcting my list of possible root-scope
thisvalues4. When a non-arrow function is called with nothing to the left of the dot, this gets a default value
When you reference
thisin a traditional function that you do not call as a method (i.e. there is nothing to the left of the dot), you get a default value forthis. In ES modules and in strict mode, that default value is (sensibly)undefined. In your console and older non-strict environments, the default value forthisis the global context object again._EDIT: Another catch here from /u/senocular. If you call a method using a
withblock (and you probably should not), you can call it on an object without putting that object to the left of the dot, so no default value.5. When using bind, call, or apply, you can set this to be whatever you want
These three function methods are alternate ways to run functions that don't get used much anymore. All three accept an explicit value for
thisas their first parameter.