0

    var sagas = [];
    var newfunction = function () {
        var saga = 'hello';
        sagas.push(function () {
            var deed = 'nice man';
            console.log(saga);
        });
    };
    newfunction();
    sagas[0]();

when we run sagas[0]() it prints hello it should print undefined as per function scoping ? I tried to think why it prints hello but couldn't

Ionut
  • 1,729
  • 4
  • 23
  • 50
j.doe
  • 1
  • 1
  • 1
    Read about [**closures**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)! – ibrahim mahrir Mar 16 '17 at 12:45
  • http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – mplungjan Mar 16 '17 at 12:46
  • reading about closures will not tell me exactly how it prints hello !! – j.doe Mar 16 '17 at 12:50
  • I think it's the same reason that `sagas` is not undefined. – ikicha Mar 16 '17 at 12:53
  • 1
    It will tell you EXACTLY why: _In JavaScript, if you declare a function within another function, then the local variables can remain accessible after returning from the function you called. This is demonstrated above, because we call the function say2() after we have returned from sayHello2(). Notice that the code that we call references the variable text, which was a local variable of the function sayHello2()._ – mplungjan Mar 16 '17 at 12:53
  • nice @mplungjan plz exaplain with a well structured example ! – j.doe Mar 16 '17 at 12:58
  • The text I pasted is from the duplicate. Find it and look above it. – mplungjan Mar 16 '17 at 12:59
  • I provided a link to MDN on the first comment! It has a lot of explanation! – ibrahim mahrir Mar 16 '17 at 13:07
  • u are giving a page full of information i agree it has a lot of information but i only want an explanation regarding this example – j.doe Mar 16 '17 at 13:26

0 Answers0