gaurav singh gaurav singh - 7 months ago 46
Javascript Question

Can we write if condition inside return

return if(ab.equals("Hello")){
return ab;
return "Hello";

Can this be done? I getting error and I'm not able to see any post or solution related to this.


In Java and in JavaScript, you cannot put any branching logic in the return; however, you can return conditionally. For your example, code, I would write it like:

return "Hello";

... since your code always has this effect (regardless of the branch). However, in other code (that can actually return different results), there are a number of different patterns that you can use:

// Pattern 1
return condition ? true_branch : false_branch

// Pattern 2:
if (condition) {
  return true_branch;
return false_branch;

// Pattern 3:
if (condition) {
 return true_branch;
} else {
 return false_branch

Personally, I tend to stick with pattern #1 or pattern #2 (I only use pattern #3 if there is an "else if" case, and even then I have a preference to put a catch all return outside of any "if...else"). The reason for this is that pattern #3 tends to result in extra levels of nesting (which can make the code more difficult to read)... as a general rule, most functions should have only one or two layers of nesting, and using pattern #2 tends to reduce the amount of nesting that occurs.

It should also be noted that there are a number of cases that beginners tend to write but that should be simplified / reduced. For example, it is not uncommon to see this pattern (or its inverse):

if (cond) {
  return true;
} else {
  return false;


return cond ? true : false;

In cases like the above, you should always simply return cond (or its inverse) directly, instead. That is, the above can be simplified to:

return cond;

In JavaScript, you may need to do a boolean conversion here, though, like:

return !!cond;