Can anyone explain why javascript return statement is used in function? when and why we should use it?
Please help me.
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 sum(num1, num2) {
var result = number1 + number2
return result
}
var result = sum(5, 6) // result now holds value '11'
2. To stop the execution of the function
Another reason that return
is used is because it also breaks the execution of the function - that means that if you hit return
, the function stops running any code that follows it.
function sum(num1, num2) {
// if any of the 2 required arguments is missing, stop
if (!num1 || !num1) {
return
}
// and do not continue the following
return number1 + number2
}
var result = sum(5) // sum() returned false because not all arguments were provided
Why we should use it?
Because it allows you to reuse code.
If for example you're writing an application that does geometric calculations, along the way you might need to calculate a distance between 2 points; which is a common calculation.
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) {
return Math.sqrt((Math.pow((x2 - x1), 2)) + (Math.pow(( y2 - y1), 2)))
}
var lineDistance1 = getLineDistance(5, 5, 10, 20);
var lineDistance2 = getLineDistance(3, 5, 12, 24);