Distinguish Your JavaScript Strings
JavaScript allows you to add methods to the String object, making them accessible to any string. However, there is an important distinction between string primitives and String objects which may bite you in the ass.
The methods are a part of the String object, not the string primitives, but
JavaScript automatically converts your primitives to objects when needed. For
example, when using 'hello'.charAt(2)
, this will work as expected. What
happens without your having to pay attention to it is that the 'hello'
primitive automatically gets converted to the String object
String('hello')
. Finally its charAt
method is invoked.
This is all fun and games, but be sure to remember this in case you want to add
a method to the String object. Taking for example the following code which
tells you if a string equals 'ward'
(a contrived example, I know). The
results may not be entirely as expected.
String.prototype.isWard = function() {
return this === 'ward';
};
'hello'.isWard(); // false
'ward'.isWard(); // Also false
The reason for this is simple. Inside our function the this
is a String
object which we are comparing to a string primitive. Since ===
takes types
into account, the comparison fails. You can solve this by either using ==
which is more permissive or by… casting your String object to a string
primitive with the toString
method. Really keeps things simple.
String.prototype.isWard = function() {
return this.toString() === 'ward';
};
'hello'.isWard(); // false
'ward'.isWard(); // true