0

When we retrieve the descriptor of an primitive type like the example below this paragraph we specify an integer as the object(which becomes the value of the property as well) and we specify the key as well which is '0'. Now because we specified an integer as the key would this mean that from ES2015 onwards, the primitive type is considered an array?

var e = Object.getOwnPropertyDescriptor([50], 0);

value of 'var e':

{
       configurable: false,
       enumerable: true,
       value: 50,
       writable: false
}

Or in the next example we pass in a string value:

var e = Object.getOwnPropertyDescriptor("hello", 0);

Which yields somewhat different results:

configurable: false
enumerable: true
value: "h"
writable: false

Now if we pass in a string it is treated as an array as well. But it appears that only the first character is being preserved as the value. Why does this happen as well?

20
  • Primitive values are not objects. In some situations, for example with a string primitive, a String object instance is automatically created around the primitive. But, again, primitives are not objects. Commented Jan 27, 2022 at 23:23
  • 1
    array isnt a primitive, its a type of object Commented Jan 27, 2022 at 23:24
  • In low level languages (C/C++), a String is simply an array of bytes. In JavaScript and other higher level languages, String is an array of bytes with a sort of wrapper around it to give it more functionality. Plus these two things are crucial for text manipulation which is used in countless places across the internet. Commented Jan 27, 2022 at 23:28
  • 1
    "hello"[0] === "h" Commented Jan 27, 2022 at 23:29
  • 1
    the String class is different from the primitive string - js just tends to coerce between them in many cases, for example, in Object.entries('abc'), the string 'abc' is converted to an object new String('abc') Commented Jan 28, 2022 at 0:05

1 Answer 1

1

When we try to get the descriptor for primitives, they are first converted to an object form as per the spec:

20.1.2.8 Object.getOwnPropertyDescriptor ( O, P )

When the getOwnPropertyDescriptor function is called, the following steps are taken:

  1. Let obj be ? ToObject(O).
  2. Let key be ? ToPropertyKey(P).
  3. Let desc be ? obj.[GetOwnProperty].
  4. Return FromPropertyDescriptor(desc).

and so any information we get from the Object.getOwnPropertyDescriptor will tell us nothing about the primitive itself, it only tells us something about the properties of the object that comes rolling out of the toObject step.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.