Javascript can jump out of the function, which can be achieved by using the return keyword. Whenever JavaScript sees the return keyword, it immediately exits the function and any variables (or values) passed after return are returned as the result.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Sometimes when you are executing a function, you want to have a quick way to exit (jump out).
You can use the return keyword to achieve this.
Whenever JavaScript sees the return keyword, it immediately exits the function and any variables (or values) passed after return are returned as the result.
This is a method I often use to ensure that a function exits immediately if certain conditions are not what I expect.
Maybe I'm expecting a parameter, but it's not there.
function calculateSomething(param) { if (!param) { return } // go on with the function }
If the param value exists, the function will proceed as expected, otherwise it will stop immediately.
In this example, I return an object describing the error.
function calculateSomething(param) { if (!param) { return { error: true, message: 'Parameter needed' } } // go on with the function }
【Related recommendations: javascript learning tutorial】
The above is the detailed content of Can javascript jump out of a function?. For more information, please follow other related articles on the PHP Chinese website!