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:
- 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;
}
- 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];
}