What is the difference? 1 works 2 doesn't!

What is the difference? 1 works 2 doesn't!
0.0 0

#1
// 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");

-------------------------------2 Starts Here---------------------------------------------

// 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");

#2

I don’t know the language, but it seems to me that the reason 2 doesn’t work is because the line
return myObj.checkProp
is calling the method checkProp of the object myObj - which doesn’t exist. Essentially, myObj is really an array.

So to return the value of the myObj that corresponds to checkProp, you need to return myObj[checkProp]


#3

#4

MyObj.checkProp in 2 is looking for property that is literally named checkProp. It doesnt exist. The only properties on myObj are gift, pet and bed.

1 works because it is looking for a prop that is the same as the value of the checkProp variable.


#5

That is not a function call - there are no parenthesis. Instead, it would be a property of myObj. But there is no such property, so it is undefined


#6

This is because of the main difference that exists between . notation and the [] notation.
In your code you are passing a variable (“checkProp”).
Since . notation only accept the keys (in your case gift,pet,bed) it takes “checkProp” as a key and check whether “checkProp” exists as a key, thus returns “Not Found”.
However [] notation sees this as a variable and takes the value assigned to the “checkProp” variable, thus returns “pony”.
I hope you are clear. :slight_smile: