Is everything in JavaScript an object? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Is everything in JavaScript an object?

I'm confused about this for a long time. But didn't will till now to understand it. I heard that when primitives such as strings are created, its done like this new String(). But the new keyword creates an object. So, I'm very confused

7th May 2020, 8:41 AM
Sajid
Sajid - avatar
6 Answers
+ 5
Numbers, booleans, strings and symbols are all primitives. An object wrapper is needed in order to use available methods of the data-type. The constructor functions like String, Boolean,etc provide that wrapping. If you want to coerce the wrapper(for example the one created when you use new String) to its primitive value use the valueOf method. let obj = new String (" "); let str = obj.valueOf(); When you use the literal form it's a primitive value. When you call the constructor it's an object wrapper of that primitive.
7th May 2020, 8:48 AM
Kevin ★
+ 3
That's what I was saying. When you do " a ".trim() the primitive is internally wrapped first, then the method is called and finally the valueOf primitive resulting value is returned.
7th May 2020, 8:58 AM
Kevin ★
+ 2
Functions that are called using new keyword are named constructor functions. new String() for example.
7th May 2020, 9:05 AM
Kevin ★
+ 1
Kevin Star thanks man. I understood
7th May 2020, 9:24 AM
Sajid
Sajid - avatar
0
Kevin Star if its a primitive value, I shouldn't be able to use methods on it such as trim()
7th May 2020, 8:54 AM
Sajid
Sajid - avatar
0
Kevin Star by calling the constructor, do you mean str.constructor?
7th May 2020, 9:02 AM
Sajid
Sajid - avatar