Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: do primitive strings have methods?

MDN states:

primitive, primitive value

A data that is not an object and does not have any methods. JavaScript has 5 primitive datatypes: string, number, boolean, null, undefined. With the exception of null and undefined, all primitives values have object equivalents which wrap around the primitive values, e.g. a String object wraps around a string primitive. All primitives are immutable.

So when we call a "s".replace or "s".anything is it equivalent to new String("s").replace and new String("s").anything?

like image 431
Pacerier Avatar asked Apr 22 '11 02:04

Pacerier


1 Answers

The technically correct answer is "no".

The real-world answer is "no, but it will work anyway". That's because when you do something like

"s".replace()

the interpreter knows that you want to actually operate on the string as if you had created it with

var str = new String("s")

and therefore acts as if you had done that.

like image 127
helloandre Avatar answered Oct 18 '22 10:10

helloandre