Friday, October 24, 2025
HomeLanguagesJavascriptWhen and why to ‘return false’ in JavaScript?

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:




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

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




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

    
    

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:




    <!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;"
                neveropen 
        </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>

    
    
  • Output:
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS