Anonymous function: Difference between revisions

Content deleted Content added
R: mention "new" shorthand lambda notation
Tags: Mobile edit Mobile web edit
Line 1,086:
This construct is often used in [[Bookmarklet]]s. For example, to change the title of the current document (visible in its window's [[title bar]]) to its [[URL]], the following bookmarklet may seem to work.
<syntaxhighlight lang="javascript">
javascript:document.title=___location.href;
</syntaxhighlight>
However, as the assignment statement returns a value (the URL itself), many browsers actually create a new page to display this value.
Line 1,092:
Instead, an anonymous function, that does not return a value, can be used:
<syntaxhighlight lang="javascript">
javascript:(function(){document.title=___location.href;})();
</syntaxhighlight>
 
The function statement in the first (outer) pair of parentheses declares an anonymous function, which is then executed when used with the last pair of parentheses. This is almost equivalent to the following, which populates the environment with <code>f</code> unlike an anonymous function.
<syntaxhighlight lang="javascript">
javascript:var f = function(){document.title=___location.href;}; f();
</syntaxhighlight>
 
Use [[Bookmarklets#History|void()]] to avoid new pages for arbitrary anonymous functions:
<syntaxhighlight lang="javascript">
javascript:void(function(){return document.title=___location.href;}());
</syntaxhighlight>
or just:
<syntaxhighlight lang="javascript">
javascript:void(document.title=___location.href);
</syntaxhighlight>