 
 
                A very short, sweet post in the series for C# developers learning JavaScript.
In this episode, we look into the void.
In C#, void is a type that has no values. We talk of a method returning void, when we actually mean the method doesn’t return anything — it’s a procedure and not a function. Well in JavaScript, all functions and methods return something and if you don’t explicitly use the return keyword, the function returns undefined. If you run the following code in Firebug, you’ll get "return type is undefined" displayed.
var testFunc = function(a) { console.log(typeof a); } console.log("return type is " + typeof testFunc(42));
Cool, eh? So,, what does this have to do with void? Well, void is an operator taking a single parameter, and that returns undefined. The parameter can be any type, including undefined. 
console.log("return type is " + typeof void("whaaa?"));
So, why exactly is this useful? Well, it isn’t really. People use void(0) as a kind of placeholder for anchor links when they don’t want to use the anchor link, but to instead attach an onclick handler for the <a> element. The browser won't reload the page if the link evaluates to false; it's as if the link were dead. Stuff that, use "#" instead, or use a real link in case the end-user has JavaScript turned off. (This philosophy is usually known as unobtrusive JavaScript: the site ‘works’ if JavaScript is turned off, but gives a better experience if it is turned on. Using void(0) as a link assumes JavaScript is turned on.)
As Douglas Crockford says, succinctly: Avoid void.
 Now playing:
 Now playing: 
    
The Alan Parsons Project - Eye in the Sky
    
(from Platinum & Gold Collection: The Alan Parsons Project) 
 Loading links to posts on similar topics...
             
            Loading links to posts on similar topics...
        
1 Response
#1 Dew Drop - February 17, 2009 | Alvin Ashcraft's Morning Dew said...
17-Feb-09 8:26 AMPingback from Dew Drop - February 17, 2009 | Alvin Ashcraft's Morning Dew
Leave a response
Note: some MarkDown is allowed, but HTML is not. Expand to show what's available.
_emphasis_**strong**[text](url)`IEnumerable`* an item1. an item> Now is the time...Preview of response