A String
is an Object
, but the primitive version exists which is created as a literal with 'Hello'
(and is by far the most common used).
People sometimes use new String()
to convert another type to a String
, for example, in a function.
function leadingZero(number, padding) {
number = new String(number);
...
}
Leading 0s are not significant in a Number
, so it must be a String
.
However, I still would have preferred to have made the Number
a String
by concatenating it with an empty String
(''
).
function leadingZero(number, padding) {
number += '';
...
}
This will implicitly call the toString()
of the Number
, returning a String
primitive.
I was reading that people say hey typeof foo==="string"
is not fool-proof because if the string is created using new String
the typeof
will give us object
.
You can make a fool proof isString()
method like so...
var isString = function(str) {
return Object.prototype.toString.call(str) == '[object String]';
}
jsFiddle.
This works in a multi window
environment. You could also check the constructor
property, but this fails in a multi window
environment.
Also refer to Felix Kling's comments to this answer.