I've been writing JavaScript for a bit and have now seen code using the idiom

var that = this;


var self = this;

Used to gain access to this through closure scope. At this point var self = this seems somewhat more common.

My question is which of these two idioms is truly the convention? Since they do exactly the same thing, are there advantages/disadvantages to either?

closed as primarily opinion-based by Ross Patterson, Dan Pichelman, GlenH7, gnat, user40980 Jul 28 '13 at 0:41

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    I don't think either is truly the convention, but self does seem to have become more common, and is certainly easier to understand contextually than that. – Michael Jul 27 '13 at 13:53
  • 1
    .bind(this) and you don't have to worry about such foolishness – rlemon Jul 27 '13 at 14:20
  • @rlemon .bind is not really cross browser (old IE) and is considerably slower in resource intensive situations, but yeah - bind is an interesting correction. – Benjamin Gruenbaum Jul 27 '13 at 14:21
  • 2
    But it is sexy and avoids that = this. – rlemon Jul 27 '13 at 14:24
  • @BenjaminGruenbaum neither is a real issue, they can be solved by the common sense custom implementation, which is included in every library anyway. Why duplicate this "idiom" when you can DRY it behind a function? – Esailija Jul 27 '13 at 14:44

Update 2018: You should use neither and prefer arrow functions that have lexical this scoping.


They are both idiomatic.

An experienced JavaScript programmer will know exactly what's going on when reading either.

It's just a variable naming thing - there is no empirical reason to choose one over the other - they function exactly the same and they're both common in big code bases of common open source libraries.

There is no reason to use one over the either. The important thing is to pick one and stick with it, and when you're joining a new code base - stick to whichever they were doing.

This related question in StackOverflow notes that self might have a really minor shortcoming where it refers to window in some browsers - so instead of getting a ReferenceError you'd get a silent error. However - this should not be the case anyway if you use a linter.

Not the answer you're looking for? Browse other questions tagged or ask your own question.