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"