How it’s happening?.. please help me

Tell us what’s happening:
Describe your issue in detail here.

When I define a object ( var obj = {,} ) out of block function , the output is “Not Found”.
like this code:

var obj = {gift: “pony”, pet: “kitten”, bed: “sleigh”, city: “Seattle”}

function checkObj(obj, checkProp) {

if (obj.hasOwnProperty(checkProp)) {
  return obj[checkProp]
} else {
  return "Not Found"
}

}
console.log(checkObj({pet: “kitten”, bed: “sleigh”}, “gift”))

On the other hand, When I define a object ( var obj = {,} ) in the function, the output is “pony”. How it’s happening??.. please help me
like code here,

function checkObj(obj, checkProp) {

var obj = {gift: “pony”, pet: “kitten”, bed: “sleigh”, city: “Seattle”}

if (obj.hasOwnProperty(checkProp)) {
  return obj[checkProp]
} else {
  return "Not Found"
}

}
console.log(checkObj({pet: “kitten”, bed: “sleigh”}, “gift”))

  **Your code so far**

function checkObj(obj, checkProp) {
// Only change code below this line
return "Change Me!";
// Only change code above this line
}
  **Your browser information:**

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

Challenge: Testing Objects for Properties

Link to the challenge:

1 Like

That’s because in your function call you defined the parameter obj: “function checkObj(obj, checkProp)”

So JS will take whatever you passed in the function call and write that into the local-bound variable instead of the global one that you defined outside.
And the object you passed in reads {pet: “kitten”, bed: “sleigh”} which doesn’t have a gift-attribute, hence it’s “not found”.

Meanwhile in the second function you are using var, which just overwrites the object you passed into the function. So ofcourse then obj is {gift: “pony”, pet: “kitten”, bed: “sleigh”, city: “Seattle”} which has a “gift”-attribute and so the function returns that.

When you create the function and write parameters into the brackets, those are basically like defining variables which only exist within the function (called “local scope”). You don’t need to define obj anywhere for it to work.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.