Implementation of onclick - javascript

Suppose that we have:
<input type="button" name="button" value="Validate Payment" onclick="Validate()" />
We can put in the onclick:
onclick="Validate"
onclick="Validate()"
onclick="Validate();"
My question is what is the difference between these 3 implementation

Will not execute the function, it will return the function (try: console.log(Validate))
Will execute the function.
Will, exactly like #2, execute the function.
So there's no difference between #2 and #3, functionally.
Please note that inline event handlers are bad practice, like mentioned in this comment by jbabey.

The difference between onclick="Validate();" and onclick="Validate()" is non existant. Semicolons are optional in javascript, so your code will be the same.
To understand the difference between onclick="Validate" and the other two, you need to understand a little about the use of parenthesis in Javascript.
Bascially,
onclick="Validate()"
will execute the function "Validate" and return whatever that function returns.
onclick="Validate"
will return the actual function "Validate".
See here for a fuller explaination: javascript syntax: function calls and using parenthesis

The parentheses () after the function name represent 'void', which is - at least by default - neccesary to execute the function properly. In some cases you would need to type in something between those parentheses, which is called 'passing a value' along with the function.
Since this (the 'void' thing) is almost, but not exactly, the same for a lot of similar programming languages (php, Actionscript, etc), and it's kind of a vague thing, I can't tell you exactly what this is for in JS though.
The difference between
onclick="Validate()"
and
onclick="Validate();" is in terms of functionality nothing. The semicolon ; separates pieces of code from each other, so it would be required if you would call another function after the Validate() function. In this case, there's no difference betweeen onclick="Validate()" and
onclick="Validate();".

There's no difference between them.

Related

why a newline between parentheses of two function calls not treat as two statements in js?

why this kind of bad design is made on js? Is there any special reason to design the automatic semicolon insertion like this?
Here is my code, It is not work in js in chrome:
(function(){console.log("abc");})()
(function(){console.log("123");})();
Here is the error:
Uncaught TypeError: (intermediate value)(...) is not a function
I know the right version of this code is :
(function(){console.log("abc");})();
(function(){console.log("123");})();
I just want to know why js syntax is designed so stupid. History reason?
I also add this question as a warning to everybody try to use the automatic semicolon insertion of javascript, please just add ; everywhere it needs, the automatic semicolon insertion of javascript is rubbish. It does not work as your expect.
The exist answer is too complex to my case, so I ask a new one:
https://stackoverflow.com/a/2846298/1586797
Another looks good but not work case 2:
x=1
(function(){console.log("123");})()
The linked question's answers explain the spec's three rules for ASI, for example this one. tl;dr:
If it doesn't work, try with semicolon.
The program should end with a semicolon.
If a statement says "can't put newline here", punish it with semicolon.
Your code does not satisfy any of the criteria.
The first line could return a function, and if so that function should be allowed to be invoked; so ( that the second line begins with is not illegal
The first line is not the last line of the program
There is no restricted syntax here.
Therefore, no automatic semicolon for you.
Some people have thus claimed that while (f(){})() syntax is good IIFE syntax, it might be good to do !f(){}() instead:
!function(){console.log("abc");}()
!function(){console.log("123");}();
This works as intended because ! just negates the (discarded) result of the function application, and also because ! as purely unary operator is an illegal character to continue the first line (i.e. f(){}()! is not a thing). This triggers rule 1, and ASI can take place.
The counterargument is that it is butt-ugly (i.e. for anyone not already familiar with the practice, it takes a while for them to understand the purpose of ! in this idiom).
Your second example is similar in nature: as far as the JS parser is concerned, 1 is a value (the fact that it is an integer and could not possibly be a function is a bit lost to it). Look at this example that syntactically is completely equivalent to yours:
a=function(f) { console.log("A CALLED!"); return f; }
x=a
(function(){console.log("123");})()
# => A CALLED!
123
Here, a is a function, so it can be invoked with function(){console.log("123");} as an argument; it returns function(){console.log("123");} unchanged after printing to the console; then () invokes that return value, and 123 is printed as well. Everything works. Thus, Rule #1 is not triggered, no semicolon for you.
(function(){console.log("abc");})()
(function(){console.log("123");})();
is equivalent to:
(function(){console.log("abc");})()(function(){console.log("123");})();
And is what is usually referred to as function currying.
For IIFEs (immediately invoked function expressions) you need to end with ;
For more on function currying see this post. Obviously your console log functions do not work as currying functions, but the syntax yourFunction(a)(b)(c) is a cool feature of the language that is used for currying.
Your code can be simplified as:
(function(){})()()();
This code will get same error.
The () expect a expression to call.
The first () call the (function(){}), the second () call the (function(){})()'s result, but the result is not a function, so it's wrong.
Without the semicolon those statements are chained. You call the first function and give the second func as argument to the return value of the first one. This could actually work, if the first function had a function as return value.
When you expand the code it becomes more obvious:
var a = function(){console.log("abc");};
var b = function(){console.log("123");}
(a)()
(b)();
the last two lines become:
(a)()(b)();
this is equivalent to
var x = a();
x(b);
since a does not return anything, it cannot call it as function with b as argument.
I think this will be clearer if you use this:
x=1
(function(){console.log("123");})()
The error states 1 is not a function. Makes it clear that (function...) is treated like the argument of a function call to 1:
x=1(function(){console.log("123");})()
Because ()() is self-invoking function and ();() are two differnt functions and interpreter is interpreting it accordingly.
Here two pieces of code are totally different for an interpreter.
(function(){console.log("abc");})()(function(){console.log("123");})();
and
(function(){console.log("abc");})();(function(){console.log("123");})();
however, this code will work fine
var a=12
var b=10
console.log(a+b)
Long answer sort :
(function(){console.log("abc");})()
is trying to immediately-invoke the preceding expression which is
(function(){console.log("123");})();
Which would be the return value of the preceding IIFE.
IIFEs can act differently in the missing semicolon situation. That is why we see code as follows:
;(function() {
console.log('abc');
})()
Please have a look of details description here : https://gist.github.com/khellang/8518964

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.

Syntax rules for parentheses in JavaScript

I'm curious about the syntax rules for parentheses in certain circumstances in JavaScript, such as in wrapping bits of code. I'm very familiar with using them for conditions, like if(this) that and to call functions, but there are a couple of other ways I've noticed myself using them and I don't actually know what the rule is, or if they're even connected.
What I've seen:
I've seen them used to wrap a function in IIFEs -the outside pair in (() => { do something })();, and also in implicit return statements from arrow functions when you want to break the line, like in React stateless functional components:
() => (
<div>
Hello World
</div>
);
I'm also aware that you can wrap a condition in multiple parentheses (for no good reason) and it doesn't break anything: if(((true))).
What I want to know:
I've discovered that I can't use parenthesis to organize my code just wherever I want to.
Are these all related? What is the rule for how/when you can wrap things? Is it all for organization's sake or is there sometimes a change in functionality (I'm thinking IIFEs in particular here)?
Thanks for any clarity on this!
There are some basic things, all different, that parentheses do:
Group subexpressions within a larger expression;
Delineate portions of some statement syntaxes (for, while, etc)
Delineate function call parameters
Delineate formal parameters in function declarations
It therefore does not really make sense to think about how parentheses can be used in a general sense, except in the first case (subexpression grouping). In that case, they work like parentheses in ordinary algebra.
In the other cases, the parentheses are part of the syntax, and they're not optional. Unfortunately in running code you can't tell one sort of parenthesis from another without simply knowing the syntax. So in
someFunction(x, (y + 1), z)
The parentheses around y + 1 are optional, and part of the expression grammar, while those around the overall list of function arguments are not optional, being required for that subexpression to be a function call.
There's really no shortcut to becoming familiar with the details of JavaScript statement syntax.

Javascript in HTML: when to use semi-colons, when to return false?

Consider the following examples of Javascript attributes in HTML elements:
<input type="button" onclick="somceFunc()" />
<input type="button" onclick="somceFunc();" />
<input type="button" onclick="somceFunc(); return false;" />
When should one end the someFunc() call with a semi-colon, and when should the semi-colon be eliminated? Also, when should one end the attribute with a call to return false;?
Thanks.
When should one end the someFunc() call with a colon, and when should the colon be eliminated?
That's a semi-colon. Always end expressions with one. Automatic semi-colon insertion has enough gotchas that you are better off just avoiding it.
Also, when should one end the attribute with a call to false?
false is a literal, not a function, you can't call it.
The usage in that example does absolutely nothing.
If you were to return false from an intrinsic event attribute (like onclick) then you would stop the default action of the control from firing. e.g. a link would not be followed. A button has no default action though.
Intrinsic event attributes should be avoided in favour of unobtrusive JavaScript.
SEMI-colons are optional in JavaScript, but it's always a good idea to include them to avoid nasty surprises, such as what happens if you try to do this:
return
{
a:1,
b:2
};
As for the false, it alone does nothing. You want to returnfalse when you want to stop the default click action from happening (usually only matters on links or form buttons).
Semicolons serve to separate statements from each other,
It is good practice to use semicolon after a function call or any JavaScript statement.
For 'false' statement :
<input type="button" onclick="somceFunc(); false;" />
This is wrong approach. Either you should call return false
Well, return false is call to prevent the action to be called.

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.

Categories