Following is the code for implementing closures to achieve privacy in JavaScript −
Example
<!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: 18px;
font-weight: 500;
color: blueviolet;
}
</style>
</head>
<body>
<h1>Using closures to achieve privacy</h1>
<div class="result"></div>
<br />
<button class="Btn">Increment</button>
<button class="Btn">Access</button>
<h3>Click on the above button to increment or try to access the variable</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelectorAll(".Btn");
function increment() {
let a = 0;
return function () {
a++;
return a;
};
}
let inc;
inc = increment();
BtnEle[0].addEventListener("click", () => {
resEle.innerHTML = inc();
});
BtnEle[1].addEventListener("click", () => {
try {
resEle.innerHTML = a;
} catch (err) {
resEle.innerHTML = err;
}
});
</script>
</body>
</html>Output

On clicking the ‘Increment’ button 4 times −

On clicking the ‘Access’ button −
