-3

I have tried declaring the variable outside the function but I get undefined.

      function scope() {
      let foo = 1;
      const bar = function() {
       return ++foo;
        }

        return bar;
        }

      const baz = scope();
      console.log(baz.foo);
      console.log(baz.foo);
Pazira
  • 51
  • 4

1 Answers1

1

Here is one way to do it, the Module pattern:

var Module = (function () {
//empty object
    var my = {};
//value
    my.value = 1;

  //method for incrementing the value 
    my.increment = function () {
        this.value++;
    };

    return my;
}());

Module.increment(); //increment the value from outside
console.log(Module.value) //log the new value

jsfiddle: https://jsfiddle.net/9dr9xy23/5/

Dream_Cap
  • 2,292
  • 2
  • 18
  • 30