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();
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();
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();
var f = function () {
var foo = 6;
function x() {
foo = 4;
};
alert(foo);
};
f();
You never call x, so the value stays the same!
var f1;
f1= function() {
foo = 4;
alert(foo);
};
f = function () {
var foo = 6;
f1();
};
f();
You must initialize the inner function
f = function () {
var foo = 6;
return function() {
foo = 4;
alert(foo);
};
};
f()();