When and why to ‘return false’ in JavaScript?

Return statements, in programming languages, are used to skip the currently executing function and return to the caller function. Return statements may/may not return any value. Below is the example of a return statement in JavaScript.

  • Example 1:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // The return statement returns
    // the product of 'a' and 'b'
    function myFunction(a, b) {
      return a * b;   
    }

    chevron_right

    
    

  • Example 2: Similarly, we can return true or false in a simple JavaScript function.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    function isEqual(num1, num2) {
        if (num1 == num2) {
            return true;
        } else {
            return false;
        }
    }

    chevron_right

    
    

These were some of the basic implementations of return false statement in JavaScript. However, there exist some more interesting implementations. Web Developers use ‘return false’ in different ways. During form submission, if a particular entry is unfilled, return false is used to prevent the submission of the form.

Below example illustrate the approach:

  • Example:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!DOCTYPE html>
    <html>
      
    <head>
        <title>
            Return false
        </title>
        <script>
            function validateForm() {
                var x = document.forms["myForm"]["fname"].value;
                if (x == "") {
                    alert("Please fill all the entries");
                    return false;
                }
            }
        </script>
    </head>
      
    <body style="text-align:center;">
        <h1 style="color: green;"
                GeeksforGeeks 
        </h1>
        <form name="myForm" 
              action="/action_page.php" 
              onsubmit="return validateForm()" 
              method="post">
            Name:
            <input type="text" name="fname">
            <input type="submit" value="Submit">
        </form>
    </body>
      
    </html>

    chevron_right

    
    

  • Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.