Home > Web Front-end > Front-end Q&A > Can javascript jump out of a function?

Can javascript jump out of a function?

青灯夜游
Release: 2023-01-06 11:17:45
Original
1917 people have browsed it

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.

Can javascript jump out of a function?

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
}
Copy after login

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
}
Copy after login

【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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template