Javascript – declare and invoke anonymous function at the same time

Javascript can declare anonymous function and call it at the same time using the following syntax:

(function (arg1, arg2, ...) {
}) (arg1, arg2, ...);

Alternatively we can also use the following syntax using exclamation mark preceding function keyword.

!function (arg1, arg2, ...) {
} (arg1, arg2, ...);

Example – involve anonymous function using brackets

<script>
(function (name) {
  document.write("Hello " + name);
  console.log("hello " + name);
}) ("John");
</script>
refresh

Example – involve anonymous function using exclamation mark

<script>
!function (name) {
  document.write("Hello " + name);
  console.log("hello " + name);
} ("John");
</script>
refresh
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments