JS Records problem . vs []

Hi there, this is definitely something very simple for you skilled folk out there but I don’t understand so would appreciate your help in understanding! The query is how come I need to use “.” notation vs notation to get the problem to work - I thought one could use either . or to access an object?

For example this works:

function updateRecords(id, prop, value) {
  if(prop !== "tracks" & value !== "") {
    collection[id][prop] = value;
  }
  if(prop === "tracks" && !collection[id].hasOwnProperty("tracks")) {
    collection[id].tracks = [];
  }
  if(prop === "tracks" && value !== "") {
    collection[id].tracks.push(value);
  }
  if(value === "")
    delete collection[id][prop];
  
  return collection;
}

but this doesn’t

function updateRecords(id, prop, value) {
  if(prop !== "tracks" & value !== "") {
    collection[id][prop] = value;
  }
  if(prop === "tracks" && !collection[id].hasOwnProperty("tracks")) {
    collection[id][tracks] = [];
  }
  if(prop === "tracks" && value !== "") {
    collection[id][tracks].push(value);
  }
  if(value === "")
    delete collection[id][prop];
  
  return collection;
}

Thank you

collection[id][tracks] = [];

In this case tracks in undefined, you have no such variable declared.
you could try

collection[id]["tracks"];

What you need to understand is that the tracks bit inside [tracks] is trying to evaluate a non existent variable reference.

If you are keen to access the property like that then declare a variable to be computed inside the brackets like:

var tracks = "tracks";
collection[id][tracks] = [];
1 Like

Anything inside the square brackets ([]) is evaluated as code before it is used as a lookup. JavaScript thinks that in the case of collection[id][tracks] that tracks is a variable (just like id is) and since that variable is undefined your code will fail.

This is similar to

console.log(thing); // prints undefined
console.log ("thing"); // prints "thing"
let thing = "stuff";
console.log(thing); // prints "stuff"

Thank you both. I retried it with [“tracks”] and that worked so that helps clear up one big part of my understanding. For the second part, I see what you mean around it being an undefined variable but is tracks not defined in the object that precedes the function or is that a scope issue or something else I need to understand better?

There are several properties called tracks defined, but there is no variable called tracks defined.

Ok I understand now. Thanks a million :grinning:

I’m glad I could help. Happy coding!