1

I have an argument to a method that I need to make sure is a string. Using var instanceof String was failing, so I did a console.log(var.constructor.name, var instanceof String and got this output:

String false

Why does JavaScript consider the constructor's name to be 'String' but doesn't consider the variable to be an instance of String?

Chuck
  • 4,662
  • 2
  • 33
  • 55

3 Answers3

3

String is a primitive so you check the type by using typeof keyword.

console.log(typeof 'some string')

You can use it as:

if (typeof variable === 'string') {
  // the `variable` is definitely a string.
}
Pawel Uchida-Psztyc
  • 3,735
  • 2
  • 20
  • 41
3

instanceof attempts to find the constructor (the right hand operand) prototype (as in the prototype property) in the object (the left hand operand) prototype chain. If the left hand operator is not an object then it wasn't really instanced by any constructor, so any left hand operator that is not an object would return false.

Now, if var (which isn't a valid identifier) is truly a primitive string then doing var.constructor.name would use an intermediate value that is a String object (usually referred as autoboxing). That would be an instance of String.

However there's no "autoboxing" when using instanceof. Therefore never an object. Therefore not an instance of any constructor.

MinusFour
  • 13,913
  • 3
  • 30
  • 39
2

String is a class/object in Javascript. So new String('hello') returns an object which is an instanceof String.

let x = 'hello'
typeof x === 'string' // returns true
x instanceof String  // returns false
x.constructor.name // returns 'String'

let y = new String('a')
typeof y === 'string' // returns false
y instanceof String  // returns true
y.constructor.name // returns 'String'

Here is what is said on String object - MDN, with emphasis added

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (that is, called without using the new keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

Frank Fajardo
  • 7,034
  • 1
  • 29
  • 47