What's the difference between "javascript:;" and "javascript:" in an anchor href attribute?
-
11The first has a semicolon, the second does not have.VisioN– VisioN2013-04-17 09:26:00 +00:00Commented Apr 17, 2013 at 9:26
-
1wondering about similarity? both are badEjaz– Ejaz2013-04-17 09:32:29 +00:00Commented Apr 17, 2013 at 9:32
4 Answers
Same as the difference between empty Javascript file and Javascript file with just a ;.
Nothing:
eval("");
//undefined
eval(";");
//undefined
See http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1
When, as the program is parsed from left to right, the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete ECMAScript Program, then a semicolon is automatically inserted at the end of the input stream.
So, empty file would be an invalid Program, then semicolon is inserted automatically, and it becomes equal to a Program with just a semicolon.
It just occurred to me that this is yet another case that prooves JSON is not a subset of Javascript: empty JSON is not valid:
JSON.parse("");
//SyntaxError: Unexpected end of input
eval("");
//undefined
:P
Comments
javascript: indicates the pseudo-protocol that can be used to evaluate JavaScript. So a single semicolon after it is equal to a script containing just ; which is an empty expression that does nothing. javascript: without anything else after it is an empty script that also does nothing. In both cases the return values are undefined which is important since a javascript: url returning something else would result in the page contents being replaced with whatever it returned.
However, you should not use javascript: urls at all - they are deprecated. Use onclick and either a useful href or # if there is no non-js version of the link. Remember to preventDefault the event in that case though.
6 Comments
javascript: returns, try javascript: 10 or javascript: 'google.com', it won't do anything.return false; on onclick or function will throw an exception and you'll have a nasty and hard to figure out bug.preventDefault() early enough (I usually do it in the first line of the event handler if it should be done unconditionally)10 being shown instead of the previous content.