Syntax: break and return

These two functions perform a similar job and so are considered together so the differences are clear. Both are used to stop the process of the statements in a function at a chosen place.

break is used to break out of a particular set of statements such as those within a loop or a switch-case statement. Any other statements within the function (that is, below the section the break releases us from) will still be performed.

return is used to stop the function completely and to return to the main script as though all the statements in the function have been completed. It can also be used to return a value to the script calling the function.

Syntax: Using break and return with a function

function functionName( parameters )
{
 list of statements in a loop which includes…

   if (statement checks for a particular condition)

  {

   (condition is met)

   break; // goes to list of statements below

}

  else

{

   (condition is not met)

   return "failed";  // leaves the function

       // and reports a value to main script

  }

list of additional statements if condition is met

}

Remarks:

These two commands have wide application in many types of script. In particular Return allows you to create self-contained generic functions to process information and provide the result such as adding tax to an amount which you can then use repeatedly.

Note:
The use of break is particularly important when using the switch case statement.

Related Topics:

Syntax: switch case