1

What does Object('abc') do?

In the Chrome console:

-> var test = Object('123')
<- undefined
-> test
<- String {"123"}
     0: "1"
     1: "2"
     2: "3"
     length: 3
     __proto__: String
     [[PrimitiveValue]]: "123"

-> var test2 = '123'
<- undefined
-> test2
<- "123"

I saw this in a presentation, though it was not explained. I would look it up myself, but I do not know what words to use. I've tried searching on the MDN Object Reference but haven't found anything yet.

Dylan Landry
  • 1,150
  • 11
  • 27
  • Read description of the link you linked in your question. It explains exactly what you're after (The Object constructor creates an object wrapper for the given value. If the value is null or undefined, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.) – Adrian Jul 20 '19 at 23:47
  • That is a simple difference in javascript between `object` and `string` type – Shankar Jul 21 '19 at 00:00
  • I did not realize that the Object constructor could be used without the `new` operator. – Dylan Landry Jul 21 '19 at 00:00
  • 1
    All constructors can be used without the `new` operator, as they are just functions, but the behavior is subtly different. In particular, the `this` context is pointed at the new object. See the documentation on the [`new` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new) –  Jul 21 '19 at 00:04

1 Answers1

3

Object is the Object constructor, which creates an object wrapper for whatever you pass in. When you pass it the '123' string, it creates an object from '123' - specifically, it assigns key-value pairs to the object for every index of the string, and assigns a length property based on the length of the string.

In contrast, a plain string, like

const str = '123';

which can have the same properties looked up on it, only gets turned as an object when necessary - that is, when the interpreter actually has to look up a property, it will create a wrapper object around the str string primitive so that properties can be looked up - kind of like how you're doing explicitly when you use Object('123').

There are very few (if any) reasons to use the Object constructor, though.

You may find Tim Down's related answer in How is almost everything in Javascript an object? helpful.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320