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

Can javascript jump out of a function?

青灯夜游
青灯夜游Original
2021-06-18 14:14:001915browse

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
}

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!

Statement:
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