in

JAVASCRIPT VOID KEYWORD | How to use Void Keyword in JavaScript

In this tutorial we will be discussing about JavaScript void keyword which entails how to use the void keyword when coding in JavaScript. In our previous tutorial we discussed about JavaScript dialogue box and we explained how to place different types of dialogue box in web pages using JavaScript. If you haven’t gone through the tutorial you can do so using the link below

Read previous tutorial on: JAVASCRIPT DIALOGUE BOX | Adding Dialogue Box To Web Pages

THE JAVASCRIPT VOID KEYWORD

The void keyword is used in JavaScript to inform a method not to return a value. So over here, an expression will be evaluated without returning a value.

The syntax for void keyword is shown below

<head>
   <script type = "text/javascript" name="javascript">
      <!--
         void func()
         javascript:void func()
      //-->
   </script>
</head>

Generating undefined value

Void can be used to intentionally generate an undefined value when a variable is checked. Example shown below

<!DOCTYPE html>
<html lang="en">
<head>
    <script type="text/javascript">
        var a, b, c;
        a=void(b=2, c=3);
        function vResult(){
            document.write("a="+a+" "+ "b="+b+" "+ "c="+c);
        }
    </script>
    <title>void keyword</title>
</head>
<body>

    <form>
        <input  type="button" value="click me" onclick="vResult()"     >
    </form>
    
</body>
</html>

RESULT

void keyword

Another Example

The void keyword can also be used to evaluate an expression for effect without the browser returning a result. The below example shows an expression alert(‘HAPPY XMAS’) been evaluated without returning a result to its local document.

<!DOCTYPE html>
<html lang="en">
<head>
    
    <title>void keyword</title>
</head>
<body>

    <a href = "javascript:void(alert('HAPPY XMAS'))">Click me</a> 
    
</body>
</html>

RESULT

void keyword Click me

Another Example

The void keyword can also be used make a link dormant. When the link is clicked no action will be taken. To achieve this, we set the value “0” inside the void bracket as shown below

void(0) this will ensure no action is returned after

<!DOCTYPE html>
<html lang="en">
<head>
    
    <title>void keyword</title>
</head>
<body>

    <a href = "javascript:void(0)">Click me</a> 
    
</body>
</html>

RESULT

void keyword Click me

lastly, please note that adding void next to a function in JavaScript will tell the function not to return a value, thereby making the function dormant.

CONCLUSION

With the help of this short tutorial we hope you fully understand the void keyword and how to use it when coding in JavaScript.

NEXT TUTORIAL: JAVASCRIPT – OBJECTS

What do you think?

javascript dialogue box

JAVASCRIPT DIALOGUE BOX | Adding Dialogue Box To Web Pages

javascript objects

JAVASCRIPT OBJECTS | Introduction to Objects in JavaScript