Anonymous Wrapper Functions in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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

raja
Published on 18-Jul-2020 07:49:14
Advertisements