1

In JavaScript, is there an instanceof that corresponds to a string literal, such that 'some string' instanceof ___ would return true? NOTE: I'm not trying to solve a problem, this is more of a knowledge/curiosity question, wanting to have a little more in-depth knowledge on this particular part of JavaScript.

jbyrd
  • 5,287
  • 7
  • 52
  • 86
  • A string literal creates a string. Any operands that you try to use with it will operate on that (resulting) string. – nnnnnn Nov 30 '16 at 03:31
  • String literal is a source code token, there is no such thing in runtime. – zerkms Nov 30 '16 at 03:31
  • 4
    Possible duplicate of [Why does instanceof return false for some literals?](http://stackoverflow.com/questions/203739/why-does-instanceof-return-false-for-some-literals) – Thilo Nov 30 '16 at 03:32
  • 3
    If it's a primitive string, it is not an object, and not an instance of anything. – Thilo Nov 30 '16 at 03:32
  • One workaround to this could be to initialize a new string via the constructor of 'some string' like this: `new 'some string'.constructor instanceof String //returns true` – hackerrdave Nov 30 '16 at 03:34
  • @hackerrdave how is it different from simply `new String()`? – zerkms Nov 30 '16 at 03:35
  • no different in this case - would be more useful pattern if you weren't certain of the type in a variable, ie: `new myValue.constructor instanceof String` – hackerrdave Nov 30 '16 at 03:39
  • @Thilo - that answers my question! Thanks. – jbyrd Nov 30 '16 at 15:18
  • 1
    @hackerrdave - I'm not trying to solve anything, so I don't need a workaround - this is purely a knowledge/curiosity question. – jbyrd Nov 30 '16 at 15:19
  • 2
    you can use `typeof` and the result would be `'string'`, if that helps. – ps2goat Nov 30 '16 at 15:25

2 Answers2

0
var simpleStr = 'This is a simple string'; 
var myString  = new String();
var newStr    = new String('String created with constructor');

simpleStr instanceof String; // returns false
myString  instanceof String; // returns true
newStr    instanceof String; // returns true
myString  instanceof Object; // returns true

you can typeof instead of instanceof when you compare strings

var simpleStr = 'This is a simple string'; 
typeof simpleStr;//returns string

refer to instanceof: instanceof

refer to typeof: typeof

Mustafa Acar
  • 412
  • 3
  • 10
-1

@Thilo answered this in his comment:

If it's a primitive string, it is not an object, and not an instance of anything.

jbyrd
  • 5,287
  • 7
  • 52
  • 86