DEV Community

Cover image for Understand Void Function in JavaScript
Pankaj Kumar
Pankaj Kumar

Posted on • Updated on

Understand Void Function in JavaScript

We all come to see javascript void function in any way while web application development. Actually it computes the given expression and then returns a value of undefined. Javascript void function is mostly used while putting an expression into a web application page that may produce unwanted effect in the application.

Also many times we come to see the use of void with html a tag in the below way:

Click here
With in html element, This is one the very common use of void function of javascript. Many times we need to call a javascript method on html element and at the same time we don’t want any other change within the page or over the browser link or page refresh. So for this purpose we mainly user javascript:void(0) in our html page.

Let’s try to understand the same thing with an example. Have a look on the below cases

Void 0
Void (0)
Void “hello”
Void (new Date())
All 4 cases are different from others but still we will get same result of undefined. In normal way it would be quite easy to use just undefined in place of above code in 4 cases. Which is much simple to understand than void also. But this is not a perfect world, especially when it comes to javascript. The main issue is that undefined is not a reserved keyword in javascript. So any value can be assigned into it if undefined will be a variable name.

Try to understand with below example:

console.log(undefined); // it will return undefined
Var undefined = “hello world‘;
console.log(undefined); it will return hello world
This problem is not with the ECMAScript version 5 and its further version in which undefined is set as global object as read only.

Alternate of javascript:void(0)

We all use javascript:void(0) with html element because it is very simple to use and it works perfectly. But it does not follow principle of unobtrusive javascript. It is always advised to use different html tags. Like on place of element button can also be used.

event.preventDefault()

We can use event.preventDefault() within onclick event to prevent from page redirection and page refresh. It works the exact same way as javascript void function do. Let's understand with example:

Double Click Me!
In above line of code, we can see the redirection path is set to Flipkart but it will not redirect to that because of event.preventDefault() set at the onclick event.

Conclusion

So in this article, We learn about the basic of void function in javascript.

That’s all for now. Thank you for reading and I hope this artible will be very helpful to learn about the basic of void function in javascript .

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

This article is originally posted over jsonworld

Top comments (0)