I’m currently working on Javascript Algorithms And Data Structures > Basic Javascript > Collection and I thought I understood dot and bracket notation, but now I’m confused. In my function, I have:
function updateRecords(id, prop, value) {
if(prop != "tracks" && value != "") {
collection.id.prop = value;
}
return collection;
}
I get an error of “Cannot set property ‘prop’ of undefined” and the first test fails, but if I use bracket notation like so:
function updateRecords(id, prop, value) {
if(prop != "tracks" && value != "") {
collection[id][prop] = value;
}
return collection;
}
then the first test passes.
Aren’t the above pieces of code doing the same thing?
You cannot access properties that are in a variable with dot notation. Dot notation only accesses the property by its specific name in the object. Bracket notation however allows you to access with variables.
If I have an object:
const person = {
name: 'Tom',
age: 28
}
Then I can use person.name or person['name'] to get the value of 'Tom'
However, if I wanted to look through the object using a variable called prop I cannot do person.prop even if prop stores the string 'name'. It will treat prop as an property and not a variable. However if I use bracket notation, person[prop], it will treat prop as a variable, and if that variable holds the string name, it will match the property and return the value 'Tom'