2

I came across this question when trying the intanceof() operator. This code returns true when working with String Objects:

var aStringObj = new String('String');
console.log(typeof aStringObj); // object
console.log(aStringObj instanceof String); // true

... and returns false with Literal Strings, like so:

var aLiteralString = "Test literal";
console.log(typeof aLiteralString); // string
console.log(aLiteralString instanceof String); // false

According to MDN, this operator tests presence of constructor.prototype in object's prototype chain, and for both; the aStringObj and aLiteralString, the .constructor.prototype are the same:

var aStringObj = new String('String');
console.log(aStringObj.constructor.prototype);// String {length: 0, [[PrimitiveValue]]: ""}

var aLiteralString = "Test literal";
console.log(aLiteralString.constructor.prototype); // String {length: 0, [[PrimitiveValue]]: ""}

Does this mean that primitive values are not instances of any prototype? And literal strings don't have a known constructor?

The more I study JS the more dumb questions arise to my head. Thanks in advance.

Community
  • 1
  • 1
  • 1
    This is not a dumb question. It's foxed many a good JavaScript developer before you. It seems downright weird that literals are not instances of a prototype, yet DO inherit their methods. – Mitya Feb 03 '17 at 14:41
  • Thanks!. The questions was marked as exact duplicate, but the first answer was clarifying. Private types don't have constructors and they are wrapped on an object when methods are called on them. – Sebastian Jimenez Feb 03 '17 at 15:08
  • @Utkanos well they don't _inherit_ the methods. Primitives actually have no methods, however if you have a string primitive _variable_ you can use a method from `String` and what happens is that the primitive is _cast_ to a String object then that object is discarded. Which leads to the present situation where you have this weird and seemingly inconsistent behaviour. – VLAZ Feb 03 '17 at 15:14
  • Thanks for clarifying, @vlaz. For all intents and purposes - i.e. in practical terms - it's as though they do inherit, but I get that technically they don't. Either way it's a bizarre situation. – Mitya Feb 03 '17 at 16:03
  • @Utkanos oh, I definitely agree - I do treat string primitives as having all the string methods. However, It's situations like these when you need to understand the difference. Basically it boils down to `"string" instanceof String` being **false** because...well, it isn't an instance of it. Until you call any method and then it VERY BRIEFLY becomes one. – VLAZ Feb 03 '17 at 22:46

0 Answers0