Table of Contents
When you're coding, you sometimes want to exit from the middle of a function.
This is useful for when you want to stop the further execution of the code, or to return a value you have already generated.
In this post, we'll learn how to exit from a function in JavaScript.
How to Exit from a function
Let's say you have a function that takes in two numbers and adds them.
However, you want to exit from the function if either number is negative.
Here's how that looks like:
JAVASCRIPTconst sum = (num1, num2) => {
    if (num1 < 0 || num2 < 0) {
        return -1;
    }
    return num1 + num2;
}
Notice how we can immediately exit the function by using the return keyword.
This is a great way to validate that the parameters passed in are valid, or simply to return back the user a value once it has been calculated.
Here's an example of a greeting that requires a name to be passed in.
JAVASCRIPTconst greeting = (name) => {
    if (!name) {
        return "Please pass a name!";
    }
    return `Hello, ${name}!`;
}
console.log(greeting("John"));
console.log(greeting());
BASHHello, John!
Please pass a name!
Conclusion
In this post, we learned how to immediately exit a function.
Just use the return keyword to exit from a function and the rest of the function will not execute.
Thanks for reading!
Getting Started with Svelte
How to Set Up Cron Jobs in Linux
Best Visual Studio Code Extensions for 2022
How to build a Discord bot using TypeScript
Getting Started with Sass
Learn how to use v-model with a custom Vue component
Using Puppeteer and Jest for End-to-End Testing
How to Scrape the Web using Node.js and Puppeteer
Getting User Location using JavaScript's Geolocation API
Getting Started with Moment.js
Creating a Twitter bot with Node.js
How To Create a Modal Popup Box with CSS and JavaScript
