Anonymous Wrapper Functions in JavaScript


Anonymous functions are used to wrap code snippets, JavaScript libraries, functions etc to control their visibility and the namespace so that there shouldn’t be any conflict with other libraries code. IIFE (Immediately Invoked Function Expressions) are used for this purpose.

Following is the code to implement Anonymous Wrapper Functions in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Anonymous wrapper functions in JavaScript</h1>
<div class="result">0</div>
<br />
<script>
   let resEle = document.querySelector(".result");
   (function () {
      resEle.innerHTML =
      "This piece of code is automatically executed as it is inside an IIFE";
   })();
</script>
</body>
</html>

Output

Updated on: 18-Jul-2020

480 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements