Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does console.dir('') print "no properties"?

Tags:

javascript

I was under the impression that strings have properties, such as match. Why does console.dir('') claim that '' has no properties (at least in Google Chrome)?

like image 918
Randomblue Avatar asked Dec 19 '11 23:12

Randomblue


2 Answers

It's because '' is a string literal, not an instance of the String "class". As properties like match are declared on String.prototype, you won't see them when using a string literal. If you use the new operator you will see what you expected:

var s = new String("hello");
console.dir(s);

Here's a screenshot from Chrome's developer tools (notice the need to expand the prototype, as the method you're expecting to see is declared on the prototype, not the String object itself):

enter image description here

like image 173
James Allardice Avatar answered Nov 18 '22 08:11

James Allardice


Likely for the same reason that console.dir(true) and console.dir(1234) say that once you turn down the knob pointing to the data. It's likely the code only iterates through properties if it's an Object. Why that turndown knob is still there is unclear.

like image 22
peller Avatar answered Nov 18 '22 09:11

peller