Tell us what’s happening:
It can’t pass the “checkObj(“house”) should return “Not Found”.” test.
Can anyone tell me where is wrong?
Your code so far
// Setup
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
// Your Code Here
var result=myObj.hasOwnProperty(checkProp);
if(result="true"){
return myObj[checkProp];
}else{
return "Not Found";
}
}
// Test your code by modifying these values
checkObj("house");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36.
Two problems with this line. First, you are using the assignment operator (=) instead of a comparison operator (== or ===). Also you are checking if it equals the string "true" and not the boolean value true - remove the quotes.
This is not doing a comparison. = is the assignment operator. It is setting the variable result to the string “true”. Because this assignment completes without error, that assignment is truthy so it always attempts to return myObj[checkProp].
If you change the assignment operator to an actual comparison operator (===), then your code will always return “Not Found” because hasOwnProperty() does not return a string value. It returns a boolean value: either true or false and “true” is not the same as true.
If your if condition is checking a boolean value, you don’t need to use a comparison operator. The contents of the if condition is evaluated as a boolean so if (thingy === true) is the same as if(thingy).
In a strongly typed language you would do something like that, but JavaScript isn’t strongly typed, so you don’t do boolean result = myObj.hasOwnProperty(checkProp) any more than you would do number myNum = 42
// 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");
I can get it to work if I change my dot notation to bracket notation for the first return statement. I don’t understand why that is. Does dot notation not work in return statements? I understand that we must use bracket notation if there are any spaces in the property name, but that is not the case here.
I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.