Pass by reference?

Can anyone tell me why all the object.num's print as 1? This is driving me mad. Somehow after the for loop the values of the object.num = 1 no matter what, even though they are never set to 1. Please copy the entire segment to debug.

<script type="text/javascript">
window.addEventListener("load", main, false);

const n = 4;

function main()
{
    var belt = new Array(4*n);
    initArr(belt);
    printIt(belt);
    populateArr(belt);
    printIt(belt);
    reorder(belt);
    printIt(belt);
}

function populateArr(arr)
{
    var a = {name:"a", num:0};
    var b = {name:"b", num:0};
    var end = arr.length;
    var i = end-1;

    for(var temp = n; temp > 0; temp--)
    {
        a.num = temp;
        arr[i] = a;
        i-=2;
    }

    i = end-2;
    for(var temp = n; temp > 0; temp--)
    {
        b.num = temp;
        arr[i] = b;
        i-=2;
    }

    return arr;
}

function printIt(arr)
{
    var tempArr = new Array(arr.length);
    for(var i=0; i < arr.length; i++)
    {
        tempArr[i] = arr[i].name + arr[i].num;
    }
    console.log(tempArr);
}

function initArr(arr)
{
    var nothing = {name:null, num:0};
    for(var i=0; i<arr.length; i++)
    {
        arr[i] = nothing;
    }
    return arr;
}

function reorder(arr)
{
    var nothing = {name:null, num:0};
    var counter = 0;
    var aIndex = 0;
    var bIndex = null;
    for(var i=0; i < arr.length; i++)
    {
        if(arr[i].name === "b" && bIndex === null)//first b doesn't get moved
        {
            bIndex = i+1;
        }

        else if(arr[i].name === "a")
        {
            arr[aIndex] = arr[i];
            arr[i] = nothing;
            counter++;
            aIndex++;
        }
        else if(arr[i].name ==="b")
        {
            arr[bIndex] = arr[i];
            arr[i] = nothing;
            counter++;
            bIndex++;
        }
    }
    console.log("count: " + counter);
    console.log("n: " + n);
    return arr;
}

</script>
Jon Skeet
people
quotationmark

Somehow after the for loop the values of the object.num = 1 no matter what, even though they are never set to 1.

Yes "they" are - "they're" set to 1 in the last iteration of this loop:

for(var temp = n; temp > 0; temp--)
{
    a.num = temp;
    arr[i] = a;
    i-=2;
}

The last iteration of that loop is when temp is 1.

Now, you've only actually got one object - and you're setting every element of the array to be a reference to that object. That's why all the values in the array look the same. If you want to create a different object each time, you should use:

for(var temp = n; temp > 0; temp--)
{
    arr[i] = { name: "a", num: temp };
    i -= 2;
}

people

See more on this question at Stackoverflow