DEV Community

mohandass
mohandass

Posted on

Closure

  • A closure in javascript is a feature where an inner function retains access to variable of it's outer function.Even after that outer function has finished executing.

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>
</head>
<body>
    <script>
        function bank() {
            let min_balance = 500;
            const actions = {
           deposit: function (amt) {
                min_balance = min_balance + amt;
                console.log("current balance is ",min_balance);

            },
            withdraw : function(amt){
                min_balance = min_balance - amt;
                console.log("current balance is ",min_balance);
            }

        }
return actions;



        }
        const check_bla = bank();
        check_bla.deposit(220);
        check_bla.withdraw(500);
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

Top comments (0)