Skip to content

Instantly share code, notes, and snippets.

@beala
Created April 21, 2013 18:26
Show Gist options
  • Select an option

  • Save beala/5430522 to your computer and use it in GitHub Desktop.

Select an option

Save beala/5430522 to your computer and use it in GitHub Desktop.
JS string weirdness
/*Strings aren't objects.*/
typeof '' // 'string'
'' instanceof Object // false
/*But they have methods.*/
'a'.concat(' string'); // 'a string'
/*A string's methods are equal across receivers.*/
'a'.concat === 'b'.concat // true
/*String's methods (capital S) aren't.*/
(new String('a')).concat === (new String('b')).concat // false
/*Even though a method isn't bound to its receiver.*/
var m = (new String('a')).concat
m(' string') // TypeError: can't convert undefined to object (receiver is undefined)
/*And a String's methods (capital S) return strings (lowercase S).*/
typeof new String('a') // 'Object'
typeof (new String('a')).concat(' string') // 'string'
/*loljs*/
@beala
Copy link
Author

beala commented Apr 21, 2013

Ah wait a minute. This turns out to be true:

a = (new String('a')).concat
b = (new String('b')).concat
a === b // true

Which vaguely makes sense. Once concat is assigned to a and b, neither has a receiver, so they're finally equal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment