# JavaScript, how to exit a function

> Learn how to exit a JavaScript function early using the return keyword, which stops execution immediately and can hand back a value or an error object.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2020-11-12 | Topics: [JavaScript](https://flaviocopes.com/tags/js/) | Canonical: https://flaviocopes.com/how-to-exit-a-function-javascript/

Sometimes when you're in the middle of a function, you want a quick way to exit.

You can do it using the `return` keyword.

Whenever [JavaScript](https://flaviocopes.com/javascript/) sees the `return` keyword, it immediately exits the function and any variable (or value) you pass after return will be returned back as a result.

This is something I use all the time to make sure I immediately exit a function if some condition is not as I expect it.

Maybe I expect a parameter and it's not there:

```js
function calculateSomething(param) {
  if (!param) {
    return
  }

  // go on with the function
}
```

If the `param` value is present, the function goes on as expected, otherwise it's immediately stopped.

In this example I return an object that describes the error:

```js
function calculateSomething(param) {
  if (!param) {
    return {
      error: true,
      message: 'Parameter needed'
    }
  }

  // go on with the function
}
```

What you return depends on how the function is expected to work by the code that calls it.

Maybe you can return `true` if all is ok, and `false` in case of a problem. Or as I showed in the example above, an object with an `error` boolean flag, so you can check if the result contains this property (or a `success: true` property in case of success).
