Learn the difficult closures concept in javascript with ease

in #utopian-io6 years ago (edited)

Repository

https://github.com/yashwanth2804/Javascript-closures

What Will I Learn?

In tutorial you will learn about

  • What is a closure in Javascript
  • How to initialize a closure and invoke it
  • A basic example of how internal works in closures

Requirements

You can execute the code in your browser ,

  • Javascript enabled browser
  • Text editor

Difficulty

  • Intermediate

Tutorial Contents

When I was learning JavaScript concepts , I had hard time understanding closures , sure some beginner might faced this too.

What is a Closure?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

taken from medium article

So with my understanding with some energy being spent on it, I made example

Please correct me if I am wrong

About the example

In this scenario, my grandpa brought 1000 BTC 🤑 and saved to Bitcoin bank,later he spent some BTC (200) and the rest is given to my Dad ,later my dad brought house (300 BTC) and given the rest to me.I donated (499 BTC) to charity 😇

A Basic Example of Closures in JavaScript:

function sum(a) {

 return function(b) {
   return a + b; // takes "a" from the outer lexical environment
 };

}

// method 1
console.log( sum(1)(2) ); // 3

/// method 2 

var call_1 = sum(1);
var call_2 = call_1(4);

console.log( call_2 ); // 5

In above example consider method 2, at first we are invoking the sum function and setting the a value (by passing as param)in that function scope.

var call_1 = sum(1);

the return function stored in var call_1, if we log call_1 we will see this

function(b) {
  return a + b; // takes "a" from the outer lexical environment
}

Now just look the variable call_1 as a typical function, now we can invoke it by calling call_1(4) which will gives the sum of two numbers, but wait we learnt that function scope variable die when scope/function ends, right. then how come the call_1 manages to get the variable defined in immediate parent even after that parent function already returned,so it should have dead.

Execution context, please refer this site.

as per it EC ,Scope chain hold the variable object of its own, outer function's variable object , and global execution context variable.

Now this is the reason why you gets var a available , when invoking call_1().make sure it gets the reference not the actual value of outer function variable.

Here is the code of Closure Bank Ltd


 var BTCbank = function(BTC_balanace) {

    return grandpa = (moneyspent) => {
        // grandpa

        BTC_balanace -= moneyspent;

        return dad = (moneyspent) => {
            // dad
            BTC_balanace -= moneyspent;

            return me = (moneyspent) => {
                // me
                return BTC_balanace -= moneyspent;
            }

        }

    }

};

// step-1
// deposit 1000 to BTCbank

var bankBalance = BTCbank(1000);


// step-2
// now grandpa spending amount is 300

var afterGrandpaSpending = bankBalance(300);

// step-3
// now grandpa spending amount is 200

var afterDadSpending = afterGrandpaSpending(200);

// step-4
// now grandpa spending amount is 499

var aftermyDonation = afterDadSpending(499);

console.log(aftermyDonation);


/// simple way 
/// console.dir(BTCbank(1000)(400)(100)(499));

Lets break down the code

Step-1:
When we call function BTCbank(BTC_balanace ), we are just initializing BTC_balanace var to 1000 and returning the function grandpa to var bankBalance.

console.log(bankBalance)

(moneyspent) => {
      // grandpa

      BTC_balanace-= moneyspent;

      return dad = (moneyspent) => {
          // dad 
          BTC_balanace-= moneyspent;
        
            return me = (moneyspent) => {
                  // me
                return BTC_balanace-= moneyspent;
           }  

      }

  }

console.dir(bankBalance)

image btc_bal

check that closure have variable BTC_balanace initialized to 1000

Step-2:

Now we can invoke bankBalance by calling bankBalance(300),then BTCbank will gets the BTC_balanace from previous initialization in immediate outer scope of current function (in previous call we already initialized it to 1000 ) and subtracts the passed value.So we do not have to track balance sheet, BTCbank will do it for you.The returned function placed in afterGrandpaSpending variable.

console.dir(afterGrandpaSpending)

console.log(afterGrandpaSpending)

(moneyspent) => {
          // dad 
          BTC_balanace-= moneyspent;
        
            return me = (moneyspent) => {
                  // me
                return BTC_balanace-= moneyspent;
           }  

      }

Step-3:

Invoking afterGrandpaSpending(200) , will triggers dad function because that is what variable afterGrandpaSpending holds,
It gets BTC_balanace from it's immediate outer function , which has 700. The passed value will be subtracted from BTC_balanace.The returned function will be stored in variable afterDadSpending.

console.dir(afterDadSpending)

console.log(afterDadSpending)

(moneyspent) => {
                  // me
                return BTC_balanace-= moneyspent;
    } 

Step-4:
Here invoking afterdadSpending(499) doesn't return a function instead a value unlike above invoked functions.The returned value stored to aftermyDonation

console.dir(aftermyDonation)

1

console.log(aftermyDonation)

1

Curriculum

This is the first tutorial in this series

Proof of Work Done

https://github.com/yashwanth2804/Javascript-closures

Sort:  

Thank you for your contribution.

  • Although this is a basic JS concept that is well illustrated elsewhere, its nice to see you exploring it, I can see you're learning as you go with this, which is good.
  • Your choice of title is filled with English mistakes, not even a complete title, please work on improving that.
  • It's good to see output at every stage of the work, explanation was fine.
  • You have some typos in your code, you used BTC_balanace in your code, while referenced it as BTC_balance in your text interchangeably. You also have lots of other English typing, punctuation, and structural mistakes, make sure to review your tutorial before submitting it.
  • Oh and that's a lot of BTC spent :)

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Really Thank you , I will do follow from the next time what you suggested. Taken to 💓.

Thank you for your review, @mcfarhat! Keep up the good work!

haha that's not what it actually means. I see what you did there! :)

Hey, @yashwanthkambala!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Congratulations @yashwanthkambala! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You received more than 50 as payout for your posts. Your next target is to reach a total payout of 100

Click here to view your Board of Honor
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:

Saint Nicholas challenge for good boys and girls

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @yashwanthkambala! You received a personal award!

1 Year on Steemit

Click here to view your Board of Honor

Support SteemitBoard's project! Vote for its witness and get one more award!

Thank you so much for sharing this amazing post with us!

Have you heard about Partiko? It’s a really convenient mobile app for Steem! With Partiko, you can easily see what’s going on in the Steem community, make posts and comments (no beneficiary cut forever!), and always stayed connected with your followers via push notification!

Partiko also rewards you with Partiko Points (3000 Partiko Point bonus when you first use it!), and Partiko Points can be converted into Steem tokens. You can earn Partiko Points easily by making posts and comments using Partiko.

We also noticed that your Steem Power is low. We will be very happy to delegate 15 Steem Power to you once you have made a post using Partiko! With more Steem Power, you can make more posts and comments, and earn more rewards!

If that all sounds interesting, you can:

Thank you so much for reading this message!