Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

Is String a Primitive type or Object in 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 ;-)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...