else return

What is Else Return?

Else return is a programming statement used in many programming languages to control the flow of execution of a program.

Explanation

In simple terms, else return statement is used to return a value from a function if certain conditions are not met. If a particular condition is true, the function will execute normally. But if the condition is false, then the program will exit the function and return a value.

The format of the else return statement is as follows:

if (condition)
{
   //execute some code
}
else
{
  return;
}

The if statement checks if a certain condition is true. If it is, then some code is executed. If the condition is false, then the program will exit the function and return a value.

Example

Let's say that we want to create a program that checks if a number is even or odd. We can use an else return statement to achieve this:

function even_or_odd(number)
{
   if (number % 2 == 0)
   {
      console.log("The number is even.");
   }
   else
   {
      return;
   }
}

So, in this example, if the number passed to the function is even, then the function will execute normally and print "The number is even." to the console. However, if the number passed to the function is odd, then the program will exit the function and return nothing.

Another way to use else return statement is by returning some value instead of just returning nothing:

function even_or_odd(number)
{
   if (number % 2 == 0)
   {
      return "The number is even.";
   }
   else
   {
      return "The number is odd.";
   }
}

In this example, if the number passed to the function is even, then the function will return the string "The number is even." If the number is odd, then the function will return the string "The number is odd."

Conclusion

Else return is a powerful statement in programming that can be used to control the flow of execution of a program. By using if statements and else return statements, programmers can create complex logic that makes their programs more efficient and effective.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe