Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy are there two kinds of JavaScript strings?
    primarykey
    data
    text
    <p>This one just stabbed me hard. I don't know if it's the case with all browsers (I don't have any other competent browser to test with), but at least Firefox has two kind of string objects.</p> <p>Open up the Firebugs console and try the following:</p> <pre><code>&gt;&gt;&gt; "a" "a" &gt;&gt;&gt; new String("a") String { 0="a"} </code></pre> <p>As you can visually observe, Firefox treats <code>new String("a")</code> and <code>"a"</code> differently. Otherwise however, both kinds of strings seem to behave the same. There is, for instance, evidence that both use the same prototype object:</p> <pre><code>&gt;&gt;&gt; String.prototype.log = function() { console.log("Logged string: " + this); } function() &gt;&gt;&gt; "hello world".log() Logged string: hello world &gt;&gt;&gt; new String("hello world").log() Logged string: hello world </code></pre> <p>So apparently, both are the same. That is, until you ask for the type.</p> <pre><code>&gt;&gt;&gt; typeof("a") "string" &gt;&gt;&gt; typeof(new String("a")) "object" </code></pre> <p>We can also notice that when <code>this</code> is a string, it's always the object form:</p> <pre><code>&gt;&gt;&gt; var identity = function() { return this } &gt;&gt;&gt; identity.call("a") String { 0="a"} &gt;&gt;&gt; identity.call(new String("a")) String { 0="a"} </code></pre> <p>Going a bit further, we can see that the non-object string representation doesn't support any additional properties, but the object string does:</p> <pre><code>&gt;&gt;&gt; var a = "a" &gt;&gt;&gt; var b = new String("b") &gt;&gt;&gt; a.bar = 4 4 &gt;&gt;&gt; b.bar = 4 4 &gt;&gt;&gt; a.bar undefined &gt;&gt;&gt; b.bar 4 </code></pre> <p>Also, fun fact! You can turn a string object into a non-object string by using the <code>toString()</code> function:</p> <pre><code>&gt;&gt;&gt; new String("foo").toString() "foo" </code></pre> <p>Never thought it could be useful to call <code>String.toString()</code>! Anyways.</p> <p>So all these experiments beg the question: why are there two kinds of strings in JavaScript?</p> <hr> <p>Comments show this is also the case for every primitive JavaScript type (numbers and bools included).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload