Tell us what’s happening:
I am on Basic JavaScript: Testing Objects for Properties Lessons. For this lesson, I am tasked with creating a function that checks if a property is in an object or not using .hasOwnProperty()
method outputting true or false depending on if it is. If someone could explain method I would be very much appreciate it.
Here are the instructions copied and pasted:
" Modify the function checkObj
to test if an object passed to the function ( obj
) contains a specific property ( checkProp
). If the property is found, return that property’s value. If not, return "Not Found"
."
So I actually passed this question this is my completed code. I used an example object to test it out in both my codes.
var myObj = {
top: "shirt",
bottom: "pants"
};
function checkObj(obj, checkProp) {
// Only change code below this line
var check = obj.hasOwnProperty(checkProp);
if (check == true) {
return obj[checkProp];
} else {
return "Not Found";
}
// Only change code above this line
}
var propName = checkObj(myObj, "top");
console.log(propName);
The code below this one is what I was writing at first. I am guessing the problem was that there was a scope limitation with the variable/ object defined in my function. BUT why in this case!? I thought if I named the object in my function argument it would be okay since the object would be passing through the function. Could someone please explain if I am making sense I would greatly appreciate it!
My code I had before I removed the variable outside the function
function checkObj(obj, checkProp) {
// Only change code below this line
var myObj = {
top: "shirt",
bottom: "pants"
};
var check = obj.hasOwnProperty(checkProp);
if (check == true) {
return obj[checkProp];
} else {
return "Not Found";
}
// Only change code above this line
}
var propName = checkObj(myObj, "top");
console.log(propName);
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
.
Challenge: Testing Objects for Properties
Link to the challenge: