Dot vs bracket notation quick question

Dot vs bracket notation quick question
0

#1

Tell us what’s happening:
in the code below, having “return myObj.checkprop” doesn’t work, but as soon as I remove the dot, and add the brackets and change it to “return myObj[checkprop]” it suddenly works. The previous bracket notation challenge before says that “If the property of the object you are trying to access has a space in its name, you will need to use bracket notation.” Since there is no space here, I’m assuming dot and bracket notation are interchangeable?

BUT I did go back on the first dot notation challenge, and it says “Dot notation is what you use when you know the name of the property you’re trying to access ahead of time.” So is it because even though we know that the property exists and we just checked in the line prior that it must exist, but the compiler doesn’t know it exists and therefore it fails with the dot notation?
Thanks, this is my first post and I’m not sure if I’ve been exhausting in my explanation, and I’m extremely new to this stuff.

Your code so far


// Setup
var myObj = {
  gift: "pony",
  pet: "kitten",
  bed: "sleigh"
};

function checkObj(checkProp) {
  // Your Code Here
  if (myObj.hasOwnProperty(checkProp)== true) {
    return myObj.checkProp
  }
  else{
  return "Not Found"
  }
}



// Test your code by modifying these values
checkObj("gift");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties


#2

So I believe the reason for this is that the code:

myObj.checkProp

is trying to check for the property named “checkProp” in the object “myObj”, which doesn’t exist.

Since what you want to do is check the object “myObj” for the value stored in checkProp you have to use bracket notation.

This is because if you want to check for a property as a string you can’t do:

myObj."gift"

you have to do:

myObj["gift"]

and since checkProp is just a variable storing a string, it has to follow that notation as well.

Does that make sense?


#3

Ohhhh I see okay that makes total sense! DUH Thanks a ton!