1

function make_withdraw(balance) {
    return function(amount) {
        if (balance >= amount) {
            balance = balance - amount;
            return balance;
        } else {
            return "Insufficient funds";
        }
    }
}

var W1 = make_withdraw(100);
W1(50); // 50
W1(60); // "Insufficient funds"
W1(40); // 10

function w(amt){
var b= 100;
if(b>=amt){b=b-amount;return b;}else{return alert("error!");}}
w(10); //90
w(10); //90

Why by assigning balance the W1 function can keep track of balance, while w function cannot?

user122049
  • 397
  • 1
  • 11
  • 1
    because [closures](https://developer.mozilla.org/en/docs/Web/JavaScript/Closures) – Kaiido Oct 05 '16 at 02:14
  • @Kaiido I am new to programming.. Could you elaborate further? Much thanks – user122049 Oct 05 '16 at 02:15
  • 2
    follow the blue rabbit and welcome to programming ;-) (there are a lot of questions that already deal with this problem and since you weren't able to find one that does answer it - because you didn't know what to search for - I doubt an answer to this question will help anyone in the future and you may want to simply delete your question if this single word helps you answer it.) – Kaiido Oct 05 '16 at 02:18
  • One returns a function, the other does not. See line 4 of your code :) – aarosil Oct 05 '16 at 02:24
  • If you are new to programming then I'd suggest avoiding closures for the time being and getting to grips with the basics. – Lee Taylor Oct 05 '16 at 02:26

0 Answers0