What does void(args) do in javascript? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does “javascript:void(0)” mean?
I want to ask a few questions regarding javascript:void(0)
<input type='submit' name='btn' value='submit' onClick='javascript:void(0)' />
Can you please explain void(0) - is it a built-in function? Does the keyword javascript represent that the code is written in javascript? If there is anything weird that you know about it, please share it with me. Thank you.

void():
This operator allows inserting expressions that produce side effects
into places where an expression that evaluates to undefined is
desired.
The void operator is often used merely to obtain the undefined
primitive value, usually using "void(0)" (which is equivalent to "void
0"). In these cases, the global variable undefined can be used instead
(assuming it has not been assigned to a non-default value).
Note, however, that the javascript: pseudo protocol is discouraged over other alternatives, such as unobtrusive event handlers.
You can read more on this similar thread: What does "javascript:void(0)" mean?

javascript:void(0) can be considered as "Do nothing". Not sure what was intended to be achieved with it here. If you wanted to prevent form submission on button click, you should have used something like
<input type='submit' value='submit' onClick='return false;' />

void is an operator that is used to return a undefined value so the browser will not be able to load a new page. An important thing to note about the void operator is that it requires a value and cannot be used by itself.

It's defining an event handling function that has no body, so nothing gets executed. You will most commonly see it used in the context of an href attribute.

Related

JavaScript: is it possible to get the attempted name of an undefined function?

I've always wondered if there was a way of improving the error message one gets when attempting to use a function that doesn't exist (or that isn't a function). For example:
document.iDontExist()
TypeError: undefined is not a function
I'd like to be able to log something like:
document.iDontExist is not a function
Just to save a few seconds. I realise I have line numbers etc, I'm just wondering whether this is possible.
Is there some property of the TypeError I could use to look up the name that was attempted?
No - not generally.
JavaScript doesn't "send messages" to invoke functions and any expression construct can have the () operator applied .. none of the browser engines try to "read into" the expression to report a more useful message.
A debugger (with break-on-exception) can be useful, but otherwise no - the exceptions will remain general without manual intervention.
Unfortunately not, but if this is an option for you, it could work...
Instead of calling document.iDontExist(), try:
(document.iDontExist || logError("iDontExist undefined")) && document.iDontExist();
This abuses logical operators to only call the function if it exists, and log an error (assuming logError exists!) otherwise.

What is the void in Javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
what is the point of void in javascript
What does “javascript:void(0)” mean?
Everywhere I see this javascript:void(0); to do nothing I think. (instead of this javascript:; can be used I think)
And that day I see javascript:void(x=document.getElementById('mytext').value);void(document.getElementById('mylabel').innerHTML=x); code in the page.
My question is very simple, why void? What void does?
MDN documentation page
This operator allows inserting expressions that produce side effects
into places where an expression that evaluates to undefined is
desired.
The void operator is often used merely to obtain the undefined
primitive value, usually using "void(0)" (which is equivalent to "void
0"). In these cases, the global variable undefined can be used instead
(assuming it has not been assigned to a non-default value).
void is an operator which returns undefined, although evaluation the following expression. The brackets are not needed.
In javascript:-urls it is used because any return value would overwrite the current document (like document.write()).
I believe this is a sort of alternative to simply terminating the click even in jQuery for example. When you attach a click handler to an anchor tag, you should always return false at the end of the handler -
$("#btn").on('click',function(){
// make toast
return false;
});
Returning false cancels any other actions that would have been executed by the event.
When you attach a javasctipt:void(0) to the onclick of an element, you are preventing that event from doing anything and leaving all the work to your JavaScript.

I get this error! [ 'return' statement outside of function ]

I was creating a form validator for a client and ran into this weird error only in Internet Explorer (Explorer) 7/8....
'return' outside of function, line 1, char 1
Of course, there was no code whatsoever on line 1. It was a simple commented statement. And there was nothing wring with it in any way. So I knew it was just a debug misdirection.
I have been pulling my hair out to understand what could be wrong here...
I have already ruled out the obvious: return statements in a loop, too many return statements in a single function, and any returns actually outside of a legitimate function definition.
What is the reason for this?
The problem was that I was using a return statement to override the default behavior for my form and it was assigned to a property, but it was not placed inside an anonymous function!
I had a form element that was set up like this:
<form name="formname" onSubmit="javascript:validateForm(this);" action="javascript:return false;" method="post" enctype="multipart/form-data">
All I needed to change was the action property to this:
… action="javascript:function(){return false};"
It now works flawlessly!
Sometimes, when you're writing back end systems where the user is expected to have JavaScript enabled in order to use the system, I feel it's fine to use javascript: href tags, since use of the system requires JavaScript anyway.
In this case, there is nothing wrong with using href="javascript:", is there?
Check to make sure you are not writing "var" in your function parameters.
In many languages you must specify the type of the argument parameters. In JavaScript you do not have to.
I was getting this error with a ModalPopupExtender. I had specified the following attribute:
OnOkScript="return false;"
Setting OkOkScript="" solved this issue for me.

What does ‘::’ (double colon) do in JavaScript?

The documentation of some JavaScript APIs shows the following snippets as an example of how to invoke some function:
<button type="button" onClick="foo.DoIt(72930)">Click</button>
<button type="button" onClick="foo.DoIt(42342::37438)">Click</button>
:: is obviously used here to allow either one or two arguments to be passed to the function.
What does :: do in JavaScript?
And how does the function know if one or two values were passed? How does it read them?
On closer look, the examples show other weird stuff like
<button type="button" onClick="foo.Bar(72//893)">Click</button>
<button type="button" onClick="foo.Qux(425;1,34::)">Click</button>
At least the // looks just wrong.
So I guess it's not some fancy new syntax that I'm not aware of, but maybe the examples are just missing quotes around a single string argument.
It was certainly not the case at the time of your question, but right now :: is a valid ES7 operator. It's actually a shortcut for bind.
::foo.bar
is equivalent to
foo.bar.bind(foo)
See an explanation here for examples:
Nothing. It is a syntax error.
>>> alert(42342::37438)
SyntaxError: missing ) after argument list
:: has nothing to do with the number of parameters. You can do that already in JavaScript with a normal comma:
function SomeFunction(param1, param2) {
//...
}
SomeFunction('oneParam'); // Perfectly legal
Also, based on Tzury Bar Yochay's answer, are you sure you're not looking at something like the following?
$('this::is all one::parameter'); // jQuery selector
In which example did you see that? So far, JavaScript does not have a double colon operator!
The double colon replaced the single-colon selectors for pseudo-elements in CSS3 to make an explicit distinction between pseudo-classes and pseudo-elements. But that is CSS3, not JavaScript! Not At ALL!
It must be a typo for
<button type="button" onClick="foo.DoIt('72930')">Click</button>
<button type="button" onClick="foo.DoIt('42342::37438')">Click</button>
It could be using ECMAScript for XML (ECMA-357 standard) which would imply the double quotes are a XPath operator.
See ECMAScript for XML
I am guessing that the parameter list for foo.DoIt() is generated by code, and one the values was empty.
Perhaps it's a typo, and the whole thing is expected to be in quotes.

What is the point of void operator in JavaScript?

I've seen some people using void operator in their code. I have also seen this in href attributes: javascript:void(0) which doesn't seem any better than javascript:;
So, what is the justification of using the void operator?
Explanation of its use in links:
This is the reason that bookmarklets
often wrap the code inside void() or
an anonymous function that doesn't
return anything to stop the browser
from trying to display the result of
executing the bookmarklet. For
example:
javascript:void(window.open("dom_spy.html"))
If you directly use code that returns
something (a new window instance in
this case), the browser will end up
displaying that:
javascript:window.open("dom_spy.html");
In Firefox the above will display:
[object Window]
The undefined value was not directly accessible in JavaScript until ES1.3.
An operator void <expression> was therefore included to permit access to this value.
It is sometimes useful, particularly when working with the Web API (e.g. event handlers), to ensure that the result of an expression is consistently undefined.
When the undefined property was added to the global object in ES1.3 the utility of void became non-obvious.
Hence your question.
The JavaScript, the void operator is used to explicitly return undefined. It's a unary operator, meaning only one operand can be used with it. You can use it like shown below — standalone or with a parenthesis.
void expression;
void(expression);
Lets see some examples:
void 0; //returns undefined
void(1); //returns undefined
void 'hello'; //undefined
void {}; //undefined
void []; //undefined
void myFunction();
void(myFunction());
If you ask why do you need a special keyword just to return undefined instead of just returning undefined: the reason is that before ES5 you could actually name a global variable undefined, like so: var undefined = "hello" or var undefined = 23, and most browsers would accept it; the identifier undefined was not promised to actually be undefined¹. So, to return the actual undefined value, the void operator is/was used. It's not a very popular operator though and is seldom used.
Let's see an example of function with void:
//just a normal function
function test() {
console.log('hello');
return 2;
}
//lets call it
console.log(test()); //output is hello followed by 2
//now lets try with void
console.log(void test()); //output is hello followed by undefined
void discards the return value from the function and explicitly returns undefined.
You can read more from my tutorial post: https://josephkhan.me/the-javascript-void-operator/
¹ In ECMAScript 5 and later, the global variable undefined is guaranteed to be undefined (ECMA-262 5th Ed., § 15.1.1.3), though it is still possible to have a variable inside an inner scope be named undefined.
Consider the following:
With Void
Without Void
<input type="text" id="foo" value="one fish" />
<input type="text" id="bar" value="no fish" />
The first link will swap the values of the text fields. The second link will open a new page with the text "one fish". If you use a javascript: link, the minute an expression returns something other than null or undefined, the browser will interpret that as what the link should do. By wrapping all expressions/statments in a void() function, you ensure your entire snippet of code will run. These days, this is primarily of use in Bookmarklets, as using an onclick attribute, or setting up event handlers in separate Javascript blocks/files is the "norm".
As for javascript: vs. javascript:void(), the first statement is ambiguous. You're saying, "hey, I want to run some javascript", but then you don't provide any code. It's not necessarily clear what the browser should do here. With the second statement you're saying "hey, run some javascript", and your code eventually returns undefined, which the browser knows means "do nothing".
Since I'm here, I'll also point out that using either javascript: or javascript:void(); has fallen out of favor with most people who care about markup. The better thing to do is have your onclick handler return false, and have the link pointed towards a page/resource that makes sense for people who have javascript turned off, or are using a javascript blocker such as NoScript.

Categories