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 Object too. I'm confused. Can someone please explain?
Thank you in advance ;-)
Definitely, String is not a primitive data type. It is a derived data type. Derived data types are also called reference types because they refer to an object. They call methods to perform operations.
' String is a primitive data type: False.
In JavaScript, strings are not objects. They are primitive values.
JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. Each element in the String occupies a position in the String. The first element is at index 0 , the next at index 1 , and so on.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With