Record Collection Questions

So I just completed the record collection lesson in the Basic JavaScript section. I’m trying to understand the reason why certain things work and don’t work because I know it will help me better problem solve.

So I have two questions:

  1. Why could I complete the activity using bracket notation to access the object properties, but it wouldn’t let me complete it when using dot notation?

if (prop != "tracks" && value != "") {
  collection[id][prop] = value;
} else if (prop === "tracks" && collection[id][prop].hasOwnProperty("tracks") === false) {
  collection[id][prop] = [];
  collection[id][prop].push(value);
} else if (prop === "tracks" && value != "") {
  collection[id][prop].push(value);
} else if (value === "") {
  delete collection[id][prop];
}

vs.


if (prop != "tracks" && value != "") {
  collection.id.prop = value;
} else if (prop === "tracks" && collection.id.prop === undefined) {
  collection.id.prop = [];
  collection.id.prop.push(value);
} else if (prop === "tracks" && value != "") {
  collection.id.prop.push(value);
} else if (value === "") {
  delete collection.id.prop;
}
  1. Could I have used a hasOwnProperty to check for whether an object has the “tracks” property? If so what did I do wrong below?

if (prop != "tracks" && value != "") {
  collection[id][prop] = value;
} else if (prop === "tracks" && collection[id][prop].hasOwnProperty("tracks") === false) {
  collection[id][prop] = [];
  collection[id][prop].push(value);
} else if (prop === "tracks" && value != "") {
  collection[id][prop].push(value);
} else if (value === "") {
  delete collection[id][prop];
}

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

You may want to review Accessing Object Properties with Variables.

Yes.

You were checking whether collection[id][prop] has the property “tracks”, but prop is tracks, so you were checking whether collection[id].tracks has the property “tracks”.

2 Likes

Thank you for the feedback! That is very helpful!