1

I am new to JavaScript objects so please bear with me.

This is my JavaScript:

var dragSources = {
  elementSources: {
    squareSource: document.getElementById('squareSource'),
    circleSource: document.getElementById('circleSource')
  },
  ifDragSource: function(elem) {
    console.log(this.elementSources.length);
  }
};

If you look at console.log(this.elementSources.length); you can probably tell that I am trying to get the length of the elementSources property. However, it returns undefined. What am I doing wrong?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
www139
  • 4,960
  • 3
  • 31
  • 56

2 Answers2

1

It's an object, not an array, therefore it doesn't have a length property.

You could use Object.keys(this.elementSources).length to get the number of keys.

The .keys() method essentially returns an array of the object's keys.

In this case, Object.keys(this.elementSources) returns:

["squareSource", "circleSource"]

Then we are just getting the length of that array, which is 2.

var dragSources = {
  elementSources: {
    squareSource: document.getElementById('squareSource'),
    circleSource: document.getElementById('circleSource')
  },
  ifDragSource: function(elem) {
    console.log(Object.keys(this.elementSources).length);
  }
};

dragSources.ifDragSource(); // 2
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
0

Technically if you need the length property in a code you have to store the length value directly in the object. Using Object.key function decreases the code efficiency . every time you invoke that function to access that value you have to re-run the same function again and again.

in order access to the length property in a js array, the BIG O is always equal to 1. because when you update the array the length property would be updated consequently But in that case the big O would be in the size of the Object and (O) = n

hadi
  • 21
  • 3