-1

I am trying to assign a value inside another function, but it is not working, what is the correct way to do this?

f = function () {
  var foo = 6;
  function() {
     foo = 4;
  };
  alert(foo);
};
f();
sajadkk
  • 744
  • 5
  • 18

4 Answers4

2

You're not calling the function. You need to do something like this:

f = function () {
  var foo = 6;
  var func = function() {
     foo = 4;
  };
  func();
  alert(foo);
};
f();

You indicated in a comment that your function is actually a callback, which is a completely different question. If you do:

f = function () {
  var foo = 6;
  somethingAsync(function() {
     foo = 4;
  });
  alert(foo);
};
f();

The function will run, but it will run the alert first, and you won't see the updated value. Instead, you should put the alert in the function itself:

f = function () {
  var foo = 6;
  somethingAsync(function() {
     foo = 4;
     alert(foo);
  });
};
f();
Kendall Frey
  • 41,292
  • 18
  • 105
  • 145
0
var f = function () {
  var foo = 6;
  function x() {
     foo = 4;
  };
  alert(foo);
};
f();

You never call x, so the value stays the same!

Fonzy
  • 681
  • 3
  • 14
-1
var f1;
f1= function() {
     foo = 4;
     alert(foo);
  };
f = function () {
  var foo = 6;
  f1();

};

f();

Link :http://plnkr.co/edit/wKDoimqEx1IuTzGPEu8c?p=preview

Pranav
  • 656
  • 3
  • 7
-2

You must initialize the inner function

f = function () {
  var foo = 6;
  return function() {
     foo = 4;
     alert(foo);
  };
};
f()();
BenMorel
  • 31,815
  • 47
  • 169
  • 296
Prabhat Jain
  • 346
  • 1
  • 8