0

I have a program (incomplete) that generates 100 divs, each with class "bar", and each with a random div.height property. Imagine a histogram if you need a visual where each bar has a random height.

I store the list of bars in a constant using:

const arrayBars = document.getElementsByClassName('bar');

Everything so far is fine.

What is strange is that, when I create two new constants (barA and barB) and try to console.log their height, they ALWAYS come back with the same height which should not be the case. I am certain that the problem is not in my random div.height generator as they work as expected in other parts of my program.

I believe the problem lies in this part of my program:

function insertionSort(unsortedArray) {
    let length = unsortedArray.length;
    for (let i = 1; i < length; i++) {
        const arrayBars = document.getElementsByClassName('bar');
        const barA = arrayBars[i].style;

        let j = i - 1;
        const barB = arrayBars[j + 1].style;

        console.log(barA.height, barB.height);
    }
}

When using the debugger, I noticed that the point in time in which barB's height becomes that of barA is for the line:

const barB = arrayBars[j + 1].style;

I feel like this is a referencing problem but nowhere in the line above do I ever set barB to refer to barA. And it can't be the fact that barB calls arrayBars, right?

In that case, why do barA and barB always have the same height?

SushiCode
  • 77
  • 1
  • 1
  • 7

2 Answers2

2

You are calling

const barA = arrayBars[i].style;

And right after, you do

let   j    = i - 1; 
const barB = arrayBars[j       + 1].style; 
                  //   j       + 1
                  // = ( i-1 ) + 1
                  // = i 
                  // => barB = arrayBars[i] = barA

So you are querying the same node two times as you move back -1 and then add +1

marks
  • 1,501
  • 9
  • 24
1

You handle your pointer wrongly.

Let's assume i is 1. You point at index 1 in the array.

const barA = arrayBars[i].style;

Now j is 0.

    let j = i - 1;

But when you say j+1 you point at index 1 again.

    const barB = arrayBars[j + 1].style;

So it is absolutely correct that barA and barB are always the same, because in both cases you point to the same index.