After reading both :
difference between "void 0 " and "undefined" , https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/void
I still have some questions.
I’ve read that
window.undefined can be overwritten vwhere void operator will return the undefined value always
But the example which caught my eyes was the one in MDN :
<a href="javascript:void(0);">Click here to do nothing</a>
In order to do nothing , I always thought I should write :
href="javascript:return false;"
And this leads me to another question : (at Href context !) :
javascript:void(0); vs javascript:return false;
What is the differences ?
Also – Does
function doWork() {
return void( 0 );
}
is exactly
function doWork() {
return undefined;
}
Thanks.
This will not work properly:
because you are not in a function. You are thinking of this:
which is correct since
return false;is placed in a function. Thefalsevalue tells theonclickto prevent the default behavior of the element.For the
returnstatement to work in anhrefattribute, you’d need a full function.but that’s just long and ugly, and as the comments note, JavaScript in an
hrefis generally discouraged.EDIT: I just learned something. Having a non
undefinedexpression as above seems to replace the elements with the return value (at least in Firefox). I’m not entirely familiar with the full ramifications of using JavaScript in anhref, because I never do it.Yes, this:
returns exactly the same thing this:
as long as the
undefinedvariable has not been redefined or shadowed by some other value.But while they may return the same thing, it’s not entirely accurate to say they are the same thing, because:
undefinedis a global variable whose default value is theundefinedprimitivevoidis an unary operator that will replace the return value of its operand with theundefinedprimitiveSo they both result in the
undefinedprimitive, but they do so in a very different way.