When I started doing full-stack JavaScript development, I started seeing some confusing variable declarations like:

var that = this;


var self = this;


var alias = this;

The scope of this in JavaScript can be confusing and frustrating if you don’t realize that this frequently gets overwritten. Let me give you a few examples of when this changes based on scope and how to avoid any issues.

Callback Functions

Callback functions, or higher-order functions, are functions that are executed in other functions. In JavaScript, functions are first-class objects, and can be used as objects - which means they can be passed as parameters, stored as variables and even be returned to be executed in other functions.

In Object-Oriented JavaScript, this will typically refer to the whole object, with all its member variables and methods. But as soon as one of your methods uses a callback function, for example, anything from a simple setTimeout() to a forEach(), the callback function overwrites this.

So let’s say we use setTimeout() and need access to one of the object’s methods inside the callback function (which is the first parameter in setTimeout). The solution is what we have before: var that = this;.

The whole code block might look like this:

doSomething() {
	//	we'd do something here

onClick() {
	var that = this;
	setTimeout(function() {
	}, 500)

Callback Functions in Iterative Functions

Another very common use case is iterative functions, like forEach(). Each iteration calls a callback function, so again, this gets overwritten inside the callback function’s scope.

componentDidMount() {
	var that = this;
	this.state.someArray.forEach(function(arrayValue, index) {
		if(my_condition_is_met) {

Callback functions are very common in some libraries, like jQuery. jQuery ajax calls also overwrite this. If you are in doubt, you can always console.log(this); just to see what this is.