0

I created the variable p with a prototype array

const p = Object.create([])
console.log(p)

I have got the next result in Firefox Object { }, and chrome Array {}. When I use array methods they work as they should

p.push(1)
console.dir(p) //Object { 0: 1, length: 1 } OK

But when I use the assignment operator, I get the next result

p[1] = 2
console.dir(p) // Object { 0: 1, 1: 2, length: 1 } length !!!
2
  • 1
    Please specify your question. Commented Nov 9, 2020 at 9:11
  • Hey, as documentation suggests Object.create returns an Object. It will only look like an Array though, as you've passed its prototype to it - it'll have instance methods like any Array instance. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Nov 9, 2020 at 9:37

2 Answers 2

2

The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.

So the result of Object.create([]) is an object. When you use "push" method for this object, actually it is found by following sequence:

  1. find the method under p object, not found.
  2. find the method under prototype reference of p, which is [], not found.
  3. find the method under prototype reference of [], which is Array.prototype.push

So when push is execute, the length is changed to 1. But if you assign value by yourself like

p[1] = 2

it is just a property under p object, length is not changed.

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

Comments

0

You need to use the Array constructor to create an Array. Also bear in mind that Arrays are also objects.

Taking the example from mozilla:

let fruits = new Array('Apple', 'Banana');

console.log(fruits.length); // 2
console.log(fruits[0]);     // "Apple"

I would recommend you to read this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array

Good luck in your learnings :)

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.