If statements in functions (best practice question)

Tell us what’s happening:
Hi,

In this particular challenge it is my understanding that you can omit the “else” part of the if statement like I did because if the if statement is true, it will return the properties’ value and break out of the function.

Both the video answer and forum post with the solution include the else, like this:


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

Is it just better practice to include the else or any other reason? I’m asking because so far in the lessons they go back and forth between the two ways of writing it.

Thanks!

Your code so far


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

function checkObj(checkProp) {
// Your Code Here
if(myObj.hasOwnProperty(checkProp))
{
  return myObj[checkProp];
}
return "Not Found";
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Challenge: Testing Objects for Properties

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

In this context it doesn’t matter, whatever you think is clearer.

1 Like

ok thanks for the quick reply!

1 Like