Faridul Hassan - 9 months ago 46

Javascript Question

Can anyone explain why javascript return statement is used in function? when and why we should use it?

Please help me.

Answer

Why is it used in a function?

**1. To return back the results of the function**

The return does what is says - it *returns* back some values to the *function caller*

```
function addNumbers(number1, number2) {
var result = number1 + number2;
return result;
}
var result = addNumbers(5, 6); // result now holds value '11'
```

**2. To break the execution of the function**

Another reason that `return`

is used is because it also *breaks* the flow of the function - that means that if you hit `return`

- the function stops running any code that is *below* it.

```
function addNumbers(number1, number2) {
// if number1 or number2 are not given stop running the rest of this function's code
if (!number1 || !number2) return false;
var result = number1 + number2; // this was not executed
return result; // neither was this
}
var result = addNumbers(5); //result now holds value 'false' since it didn't provide all the necessary arguments and function addNumbers() returned 'false'
```

Why we should use it?

Because you should be a *lazy programmer*

Let's imagine that you are writing an application that does geometric calculations - Surely along the way you would want to calculate... e.g *the distance between 2 points* - which is a common calculation.

- Would you write the formula again each time you need it?
- What if your formula was wrong? Would you visit all the places in the code where the formula was written to make the changes?

No - instead you would wrap it into a function and have it return back the result - so you write the formula once and you **reuse** it everywhere you want to.

```
function getLineDistance(x1, y1, x2, y2) {
var distance = Math.sqrt((Math.pow((x2 - x1), 2)) + (Math.pow(( y2 - y1), 2)));
return distance;
}
var lineDistance1 = getLineDistance(5, 5, 10, 20);
var lineDistance2 = getLineDistance(3, 5, 12, 24);
```

Source (Stackoverflow)