Is a return statement always necessary?

When executing a function, for example a click event. Is it necessary to specify ‘return’ if certain conditions are not met? For example:

$('#box').on('click', function() {
  if (gameInProgress === false) {
    ..do some stuff
  } else {
    return;
  }
}

Is it good practice to have the else statement or can this be excluded?

Return can be used to get a value if you need it or return other function and use that function in your code for example.Also if you have some lines of code after some expression or statement and you don t want the code to continue if a certain condition was met you can use return and the code won t execute further.

1 Like

This depends entirely on what your intended outcome is, as omitting the ‘else’ clause can have an unintended outcome. If the expression in the ‘if’ statement is true, the body in the ‘else’ clause will NOT be executed; if the expression is false, the body in the ‘else’ clause WILL be excuted. Sort of like an “either-or” situation—either the code in the ‘if’ block runs, or the code in the ‘else’ block runs, and never both of them. However, if you omit the ‘else’ clause, the next statement following the ‘if’ statement will be executed regardless of whether the ‘if’ expression was true or false.

if (a < b) {
  console.log("a less than b");
}
console.log("a greater than or equal to b");
// runs whether or not a is less than b
// so the output could be:
// a less than b
// a greater than or equal to b
// talk about confusing to the end-user!
if (a < b) {
  console.log("a less than b");
} else {
  // runs only when a is NOT less than b, so the output will never be confusing
  console.log("a greater than or equal to b");
}

You don’t always need to have an ‘else’ clause on an ‘if’ statement, but it does make sense in many situations. Obviously, not all situations. It depends on what you want to happen.

1 Like