Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Functions Create Reusable Code with Functions Using Multiple return Statements

Adrian Rojas-Baez
Adrian Rojas-Baez
3,197 Points

Why does the statement if (fieldTest) { } return true? Does if(x) {} always return a true statement?

function isFieldEmpty() { const field = document.querySelector('#info'); if (!field.value) { // if (field.value === '') is the same as if (!field.value) return true; } else { return false; } }

const fieldTest = isFieldEmpty();

if (fieldTest) { alert('Please provide your information.'); }

1 Answer

Steven Parker
Steven Parker
229,732 Points

The statement if (x) will test the value of "x", whatever it may be. In this case, it is being used to check the value of the HTML field with the ID of "info", which will be "falsey" when it is empty.

Also, you don't need to test a value if you are only going to return it, so this code:

  if (!field.value) {
    return true;
  } else {
    return false;
  }

... can be simplified to just this:

  return !field.value;