Question on Record Collection Task

So I understand most of what’s going on with the below solution. Just a quick question, when updating ‘5439’ , obviously the prop ‘artist’ does not exist, so when this piece of code is performed ’ object[id][prop] = value;’. Does it just make the new prop in the class as ‘artist’ does not yet exist.
Just seems weird to me that you don’t need to make that prop first before adding a value to it . Hope this makes some sense.

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

// Only change code below this line
function updateRecords(object, id, prop, value) {
  if (prop !== 'tracks' && value !== "") {
    object[id][prop] = value;
  } else if (prop === "tracks" && object[id].hasOwnProperty("tracks") === false) {
    object[id][prop] = [value];
  } else if (prop === "tracks" && value !== "") {
  } else if (value === "") {
    delete object[id][prop];
  return object;

updateRecords(collection, 5439, 'artist', 'ABBA');```

You are making the property by assigning a value to the property. In an object, you create or update a key-value your the same way.

1 Like

This let object = {prop: 'value'} is the same as this

let object = {};
object.prop = 'value';

If something can have a property you can assign the property in either of the methods above, but if something cannot have a property such as undefined it would throw a syntax error. If you need to assign a value dynamically you of course need to use bracket notation. You can set properties of some primitives data types such as a number and a string and it will not throw an error, but it will not actually do anything because of what is actually going on when you attempt to do that and if you are interested in that I will link some stuff for you to read about what is going in there.

Would love any links to additional material you have. Thanks !

This talks about object wrappers, and I feel it may give you a better idea of how properties work.
This one is the documentation on the Object Model by MDN

1 Like

Thanks! Appreciate it!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.