Basic Javascript: Record Collection - Push Nested Object

What is the difference between normal assigning vs pushing? With respect to the question which wants to keep the newly inserted element at the last.

Question link: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/record-collection

Please see the cases below case 1 and case 2 in the code:-

// Setup
var collection = {
  2548: {
    album: "Slippery When Wet",
    artist: "Bon Jovi",
    tracks: [
      "Let It Rock",
      "You Give Love a Bad Name"
    ]
  },
  2468: {
    album: "1999",
    artist: "Prince",
    tracks: [
      "1999",
      "Little Red Corvette"
    ]
  },
  1245: {
    artist: "Robert Palmer",
    tracks: [ ]
  },
  5439: {
    album: "ABBA Gold"
  }
};

// Only change code below this line
function updateRecords(id, prop, value) {

    if(value!="")
    {
    if(prop=="artist")
    {
        collection[id][prop]=value;
    }
    
    else if(prop=="tracks")
    {
        if(!collection[id][prop])
        {
            collection[id][prop]=[]; 

//at this point tracks property is empty after previous line so why necessary to push?            
          collection[id][prop].push(value);          //case 1 using push
         // collection[id][prop]=value;				//case 2 without using push
            
           console.log('Inside tracks '+collection[id][prop]);
        }
        else
        {
            console.log("Prop is present with elements in it");
            
        	collection[id][prop].push(value);
        }
    }
        
    else if(prop=="album")
    {
        collection[id][prop]=value;
    }        
        
        }
           else
   {
    delete collection[id][prop];   
   }
   console.log('End Console '+ collection[id][prop])
   console.log("_________")
  //return collection;
}

updateRecords(5439, "artist", "ABBA");
updateRecords(5439, "tracks", "Take a Chance on Me")
updateRecords(2548, "tracks", "")
updateRecords(2468, "tracks", "Free")

In order to add items to an array via the push method, you have to have an array first. In the case where there is not an existing “tracks” property (which should be an array of strings), you must first assign an empty array to a “tracks” property and then use the push method to add an actual track. Another approach is to assign an array that already has the track as its only element.

** I have used this to assign an empty array to “tracks” property**

collection[id][prop]=[];

Now at this point tracks property is an empty array so why necessary to push?
why can we not use this directly?

 collection[id][prop]=value;

In the first you assign an empty array to the property represented by prop. In the second, you assign value to the property represented by prop. To add elements to an array, you use push.

1 Like

thanks! @RandellDawson