Is String a Primitive type or Object in Javascript? Source says Undefined, Null, Boolean, Number and String are all primitive types in Javascript. But it says String is an O
There is a String object and there are string literals.
You can call any string method on a literal and you can call any string method on a string object.
The major difference is that a string object generates a new object so new String("foo") !== new String("foo")
That and a String object is type "object"
and not "string"
if(typeof(s) == "string" || s instanceof String){
//s is a string (literal or object)
}
Credits to @Triynko for the snippet in the comments
var a = "string";
typeof a // yields "string"
var a = new String('string');
typeof a // yields "object"
JavaScript has both primitive and object Strings.
> var foo = "foo"
undefined
> var bar = new String("bar");
undefined
> foo
"foo"
> bar
String
> typeof foo
"string"
> typeof bar
"object"
Actually the same answer applies to: strings, numbers, booleans. These types have their primitive and object version which are coerced in the application runtime, under the hood (without your knowledge).
JavaScript is weakly typed. This means that whenever your code wants to perform an operation with invalid datatypes (such as add a string to a number), JavaScript will try to find a best match for this scenario.
This mechanism is also called, as mentioned above, coercion.
You can find following code confusing:
> "hello world".length
11
because "hello world"
is a string literal, i.e. a primitive. And we know that primitives don't have properties. All is right.
So how does that work? Coercion - the primitive is wrapped with an object (coerced) for just a tiny fraction of time, the property of the object is used and immediately the object gets disposed.
So primitives are casted with their object wrapping versions - but it also works the other way round as well. Consider following code:
> String("hello ") + String("world")
"hello world"
> Number(2) + 3
5
The objects are down-casted to their primitive versions in order to accomplish the operation.
Read this brilliant explanation to learn more.