Tell me about the return
function as a kid, I can’t figure out how to use it in JavaScript.
Answer 1, authority 100%
- This is not a function, but a language construct.
- A function in JS must return something. Even without
return
,undefined
will be returned.
And if you need to return something meaningful, then using this operator you can implement it by telling the interpreter what to return.
Examples:
// Perform calculations without returb
function withoutReturn (a, b) {
// There is a result, but since this is an internal variable and it is not returned, the result dies with it
// You can set it to an external variable, but this is fu, you don't have to be, keep the functions clean
let c = a + b;
// This could be here, although this is a procedure, not a function
document.querySelector ('# test'). innerHTML = "Test";
}
function withReturn (a, b) {
let c = a + b;
// Here we did something and give the result, that is, the meaning as a function is present
return c;
}
// undefined - waited for the addition, which happened, but did not return anything (i.e., the undefined marker was automatically returned)
console.info (withoutReturn (5, 5));
// 10 - added and returned, what is needed
console.info (withReturn (5, 5));
& lt; span id = 'test' & gt; & lt; / span & gt;
Answer 2, authority 17%
The return
statement has two purposes.
First, it is exit immediately from the function. Those. the operator transfers control to the code that called the current function.
Example:
function twice (a) {
if (isNaN (a)) return; // Conditional exit without result (c undefined)
return 2 * a; // Exit with the desired result
a + = 5; // Code after calling return cannot be executed
}
Generally speaking, there are several ways to exit a function:
- Reaching the last statement (the function code simply ends, similar to
return;
orreturn undefined;
) - Direct call of the
return
- Throwing an error, exception (
throw 'something'
,throw new Error
)
In this case, “stack unwrapping” is performed, we go down the call stack until we encounter an exception handler (constructiontry {} catch (e) {}
)
statement
Secondly, it is a return of a value , the so-called “function result”.
Example:
function max (a, b) {
if (a & gt; b) return a; // Conditional exit with result a
return b; // Unconditional exit with result b
}
PS : This actually applies to many programming languages, not just javascript.