Is String a Primitive type or Object in Javascript?

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).

Coercion

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.

Primitives and Properties

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.

Coercion working both ways

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.

Leave a Comment