What is the void in Javascript [duplicate] - javascript

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.

Related

Don't understand a javascript snippet

I am currently editing a theme code in which the following javascript snippet occurs:
...
void 0 === Cookies.get("Key") && e("#modal").fadeIn(),
e("#modal .newsletter-close a").on("click", function (e) {
e.preventDefault();
}),
...
First of all, I don't understand the first line.
void boolean && function
Secondly, I don't understand that the functions in the snippet are separated with commas even though these functions are all inside another one and not in an object.
I hope someone can explain what is happening there (not specifically in this snippet, but generally for this spelling) or give me a keyword to google for
void forces the return of undefined. This is rarely desirable, however it also forces the line after it to execute, and then throws away the result of that execution. Most often you'll see it used to stop a link from going to it's href. Instead, it'll have something like href="javascript:void(performAction());". In which case, clicking the link will cause the performAction() function to fire and the whole thing returns undefined and the anchor doesn't go anywhere.
The double ampersand is a logical operator, and is saying if the cookie portion is true, and the modal portion is true, then the next thing.
The comma operator acts as a shorthand break between statements.
This is a shorthand way of saying, immediately execute this shorthand if, if the Key cookie is equal to 0 (likely means not set), and the modal is faded in, then attach the click event to the close button of the modal.
More than likely, this modal is dynamically created, and the click event isn't attached when the $(document).ready() function fires, because the modal doesn't exist yet. This is a way to allow the modal to have a click event in the shortest amount of code they could think of.
More here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void

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

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.

Why does the void operator invoke GetValue(expr) when it always evaluates to undefined?

The void operator in JavaScript will call the internal GetValue(expr), but always return undefined, regardless of what value or expressions are.
The spec says:
11.4.2 The void Operator
The production UnaryExpression : void UnaryExpression is evaluated as follows:
Let expr be the result of evaluating UnaryExpression.
Call GetValue(expr).
Return undefined.
GetValue must be called even though its value is not used because it may have observable side-effects.
My question is, why? What sort of observable side-effects could happen? Can we demonstrate how void might alter program flow, and discuss what would happen if we didn't run GetValue?
If you're writing a program with no side effects, then a function that always returns undefined isn't helpful because it does not return useful information back to the caller. In that case, you might as well not call the function at all if you always know what you'll be getting back.
However, if a language has "side effects", even functions that return undefined can still be programatically useful. "Side-effects" is a technical term for some effect that's not a part of the return value of a function. As a concrete example, mutating the DOM is a side effect that doesn't compute and return a useful value, but you still want the state of your DOM tree to mutate. Playing a sound is also a side effect.
As a side note, void can be useful since, grammatically, it forces an expression context, so that things like function expression values can be expressed unambiguously. e.g.
void function(){alert('hi')}()
I've seen this a few times with use cases such as:
javascript:void window.open("http://foo.com")
This can be used in bookmarklets to avoid changing the value on the address bar, but still executing the code - so you would obviously want to evaluate that function and not just ignore it.
It's also sometimes used by paranoid programmers who don't trust that undefined was not overridden somewhere. If you really need to know undefined, you can compare it to void 0 (since void is a reserved keyword, it cannot be used as a function name).

Javascript function which does not return a value in every case [duplicate]

This question already has answers here:
What does javascript function return in the absence of a return statement?
(3 answers)
Closed 7 years ago.
If I have a javascript function, it is possible that I do not return a value from every code path, e.g:
function f()
{
if (checkSomething())
{
return 42;
}
// no return statement here
}
Is this valid javascript or does it only work by chance (i.e. might there be problems when run in some browsers)?
Yes, it is valid javascript. If checkSomething() evaluates to false, it will return undefined.
See http://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope for more details.
Althought, you should note that returning different types of data (In this case, an integer or undefined) is bad practice.
Since Javascript is a loose language compared to compiled ones, you can get away with things that most compiled languages will not allow. So yes, it can be done, it's just a matter of whether you want to do something like this. If you were to try to compile this code in a language such as C# or similar, the compiler would generate an error.
I am not trying to critique your code, just offering a suggestion on good design. Functions are intended to return values on all code paths and it is up to the calling code to check that return value and decide what to do. You could check the return value for undefined or whatever it is when checkSomething() returns false or you could set the value to something more meaningful that the calling code can check upon return. You may have return values that mean certain things to the caller. -1 means one thing, -2 means something else.
Hope this helps.
This JavaScript will work, just keep in mind that if you try to read the return value of f it will be set to undefined if no return statement is executed.
Personally I think this code is a little weird. If you are going to return from one code path, I suggest returning from all other possible code paths as well. That way someone reading and working with your code knows exactly what to expect.

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