In the world of Javascript, primitive values like numbers and strings do not have methods attached to them.
When a method is called on a primitive value, it gets converted into its object form, similar to how "boxing" works in languages like Java or C#.
Let's look at a simple example that highlights this difference:
// number primitive
let primitive = 12;
console.log(primitive);
// number object
let object = new Number(12);
console.log(object);
The object forms of primitives generally behave similarly to their primitive counterparts, but there are some differences, such as with equality comparisons:
console.log(12 == 12); // true
console.log(new Number(12) == new Number(12)); // false
// mixed comparisons
console.log(new Number(12) == 12); // true (boxed value will be unboxed)
console.log(new Number(12) === 12); // false (strict equality)
The reason why your second example 'a'.in(['a'])
isn't functioning as expected is because Array.prototype.indexOf
uses strict equality (===
) when checking each element.
The string this
is currently in its object form, while the 'a' in the array is in its primitive form, making them not equal.
To make the in()
function work properly, you'll need to "unbox" the string value using the Object.prototype.valueOf()
method, which returns the primitive value:
String.prototype.in = function(input) {
return input.indexOf(this.valueOf()) > -1
}
console.log('a'.in('abc')); // true
console.log('a'.in(['a'])); // true