Categories
JavaScript

How to terminate function in JavaScript?

Sometimes when we are coding we need to terminate the function. The thing is, we always “terminate” or exit a function either by calling callback() or just our function finishes its “assignment”. We are not talking about those cases, we are talking about cases when we need to exit a function before it finishes.

We can terminate any function at any point by using keyword return. Whatever we pass immediately after return, it will be returned back as a result. We can pass variable, string, number, boolean, array, anything we want. But if you write anything after that it will not be executed or returned because as soon as we use return JavaScript immidiatelly terminates the function.

function doSomeStuff() {
    if (!something) {
        return false;
    }
}

The previous function will exit and it will return false. But we could also return anything else, like in the example below.

let username = '';

function checkUsername(username) {
    return {
        code: 403,
        message: 'Unauthorized access! Username required'
    }
}

If we want to return multiple things, we have to use either array or object.

We do not always want to exit a function when there is some error. We can terminate it when we want to return something to another function.

function checkSomething() {
    //We did some coding here
    if (data) {
        return true;
    }
}

function checkAlso(param) {
    if (param) {
        //do code
    } else {
        return false;
    }
}

let someCheck = checkSomething();
checkAlso(someCheck);

After return returns what is right after it, our function stops executing.

function doSomething() {
    if (!some) {
        return false;
        // WHATEVER WE WRITE AFTER THIS WILL NOT
        // BE EXECUTED
    }
}

If you have any questions or anything you can find me on my Twitter, or you can read some of my other articles like Cool HTML tags that could help us