-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
  • 764
  • 1
  • 5
  • 19

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
  • 43,130
  • 20
  • 110
  • 148
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
  • 691
  • 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
  • 666
  • 3
  • 7
-2

You must initialize the inner function

f = function () {
  var foo = 6;
  return function() {
     foo = 4;
     alert(foo);
  };
};
f()();
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Prabhat Jain
  • 346
  • 1
  • 8