Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is String a Primitive type or Object in Javascript?

Tags:

javascript

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

like image 367
Imran Avatar asked Oct 06 '11 13:10

Imran


People also ask

Is string a primitive or object?

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.

Is string a primitive type?

' String is a primitive data type: False.

Is string a object in JavaScript?

In JavaScript, strings are not objects. They are primitive values.

Is string a type in JavaScript?

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.


1 Answers

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.

like image 53
ducin Avatar answered Sep 28 '22 11:09

ducin