+ 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
6 Respuestas
+ 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.
+ 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.
+ 2
Functions that are called using new keyword are named constructor functions. new String() for example.
+ 1
Kevin Star thanks man. I understood
0
Kevin Star if its a primitive value, I shouldn't be able to use methods on it such as trim()
0
Kevin Star by calling the constructor, do you mean str.constructor?