JavaScript Void Keyword

please click here for more wordpress cource

In JavaScript, the void keyword is an operator that takes an expression and evaluates it, but then always returns undefined. It is often used in event handlers for hyperlinks and buttons to prevent the default behavior of navigating to a new page or submitting a form.

Here is an example of using the void operator in an HTML hyperlink:

<a href="javascript:void(0);" onclick="myFunction()">Click me</a>

In this example, the href attribute of the hyperlink is set to "javascript:void(0);", which means that clicking the link will not cause the browser to navigate to a new page. Instead, the onclick event is triggered, which calls the myFunction() function.

The void operator is used in this case to ensure that the hyperlink does not perform any default action when clicked. The expression passed to void is simply 0, which is evaluated but then discarded because void always returns undefined.

The void operator can also be used to create self-executing anonymous functions, like this:

void function() {
  // do something here

In this example, the void operator is used to suppress the return value of the anonymous function, which is executed immediately. This technique is sometimes used to create a block of code that is executed once, without creating any variables or functions in the global scope.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *