javascript: do primitive strings have methods?

No, string primitives do not have methods. As with numeric primitives, the JavaScript runtime will promote them to full-blown “String” objects when called upon to do so by constructs like:

var space = "hello there".indexOf(" ");

In some languages (well, Java in particular, but I think the term is in common use) it’s said that the language “boxes” the primitives in their object wrappers when appropriate. With numbers it’s a little more complicated due to the vagaries of the token grammar; you can’t just say

var foo = 27.toLocaleString();

because the “.” won’t be interpreted the way you’d need it to be; however:

var foo = (27).toLocaleString();

works fine. With string primitives — and booleans, for that matter — the grammar isn’t ambiguous, so for example:

var foo = true.toString();

will work.

Leave a Comment

tech