Skip to content

JavaScript, how to exit a function

The Valley of Code

Your Web Development Manual

How to quickly end a JavaScript function, in the middle of it

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

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:

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).

โ†’ Get my JavaScript Beginner's Handbook
โ†’ Read my JavaScript Tutorials on The Valley of Code
โ†’ Read my TypeScript Tutorial on The Valley of Code
  • THE VALLEY OF CODE (+ PRO), your web development manual
  • I wrote 15+ free coding BOOKS, download them here
  • SOLOPRENEUR LAND the missing MBA for wannabe solopreneurs craving a life with more freedom, control, fulfillment and purpose (summer 2024)