Can anyone explain why javascript return statement is used in function? when and why we should use it?
Please help me.
You use a return statement for two reasons:
To return a specific value from a function.
To finish the execution of the function before the last line of code in the function.
Without any return value;
statement, the function does not return a specific value (technically the return value is undefined
).
Without a specific return statement somewhere in the function, the function runs until the last line of code in the function.
Examples:
function add(x, y) {
// return a sum of the two arguments
return x + y;
}
console.log(add(1, 3)); // 4
function findParm(str, key) {
if (!str || !key) {
// invalid parameters, so return null
return null;
}
var pieces = str.split("&");
for (var i = 0; i < pieces.length; i++) {
var loc = str.indexOf(pieces[i] + "=");
if (loc >= 0) {
// when we've found a match, return it and finish execution of the function
return str.slice(loc + key.length + 1);
}
}
// no match found, return null
return null;
}
var str = "user=John&login=yes"
findParam(str, "login"); // "yes"
it's used to return a value from the function.
Let's say you want a function to do some calculation... for a simple example, like calculate a div box's left position on the browser screen.
you call the function and give it the html selector, then the function 'returns' you the left position value.
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);