Profile Lookup - dot vs brackets

I do understand the challenge and got the code correctly but I’ve been struggling to fully understand when to use a dot (contacts[i].firstName) and when brackets (contacts[i][prop]) inside the for loop

full code of my for loop is this and it works but I can’t figure out why contacts[i][firstName] doesn’t work or vice versa contacts[i].prop

for (let i = 0; i < contacts.length; i++) {
        if(contacts[i].firstName === name) {
            return contacts[i][prop] || "No such property";

link to challenge:

Is there a link to the challenge?

try reading this, see if it helps

have edited my post, link is included now

The challenge is named: Profile Lookup
Are you looking up anything?
Hint: Take a look at ieahleen link onto how to do this

Thanks but it’s still not clicking in my brain. I don’t see the difference between firstName and the prop . Both are always strings, right?

When you use dot notation, the text after the dot must exactly match the property name.
this.thing is equivalent to this["thing"].
You need to use bracket notation any time the property name is stored in a variable. You also need it if the name contains a space because you cannot do this.thing with a space.


The dot and bracket notation use in different places.
In your case, the square bracket [i] was used as index, while the .firstName is a property selector. The context in which you use these is what’s confusing.

For example, when you are working with an object, you can use both the dot and bracket notation:

const nameObj = { "name1" : "Free", "name2" : "Code", "name3" : "Camp" };

In the above example, both notation does not make a difference because they’re both are selecting a property.

Let’s look at some other cases where you would prefer to use one over the other.

Case 1

const nameObj = { "name 1" : "Free", "name2" : "Code", "name3" : "Camp" };
nameObj.name1;  //This will return undefined
nameObj["name 1"] //This will return "Free"

The reason is because in dot notation the property acts like a variable following variable rules. Which means no spaces allow. While the bracket notation, you can insert a string inside the bracket, treating the property as a string and not a variable.

Case 2

const personObj = [
   { "name" : "David", "age" : 100 },
   { "name" : "Samantha", "a g e" : 50 }

Now we are using both arrays and object in the same context. Array first, and then object second. Let’s try to get the age of Samantha.

To get the age, you’ll have to be aware which data type you are working with first.
In this case, it is an array.

In here, I am using a bracket notation, because I am working with an array.


Next, I am working with an object, so both dot notation and bracket notation works, it must follow the rules in case 1. Since age is written as “a g e” (with spaces in between), we will write it with square bracket.

personObj[1]["a g e"]; //50
personObj[1].name; //Samantha

Hope that helps.