In the second function, bar is out of scope - it only exists in the function "foo()"; in the function "callback()", bar does not exist and that is why you get the bar is not defined error. I would change it to accept a parameter and print that parameter, like so:
var foo = function (callback) {
var bar = 2;
callback(bar);
}
var callback = function (bar) {
console.log(bar);
}
In this way, callback will print whatever is the passed in value of bar. Another way to do this (depends on your application but could generally be considered less recommended) would be to define bar as a global variable, outside of either function:
var bar = 2;
var foo = function (callback) {
callback();
}
var callback = function () {
console.log(bar);
}
Either way works, but the first method is better encapsulating your code and not making use of a global variable.
EDIT: Here's a less confusing version of the first method, where it's better not to use "bar" variable name in 2 different uses, just for sake of readability:
var foo = function (callback) {
var bar = 2;
callback(bar);
}
var callback = function (myBarParam) {
console.log(myBarParam);
}
Hope this is helpful!
baris visible only inside functionfoo, where it was declared.callbackis not defined insidefooin the second case. Google forjavascript closures.