Hello I am new to node js and I am trying to write a simple callback function however get "ReferenceError: sum1 is not defined", can anyone help me? code:
sum1(1,2, function(sum){
console.log(3 + sum);
});
sum1 = function (a,b, callback){
callback(a + b);
};
However, I tried to use
function sum1(a,b,callback){...}
and it works. Is this a naming problem? Can anyone explain a little bit?
You have to define the function before you call it. When you use the form:
sum1 = function() {...}
to define your function, that definition MUST occur BEFORE you use the function. That's because the function is not assigned to the sum1
variable until that line of code executes. So, if you try to execute sum1(...)
before that line runs, then sum1
is not yet defined and you get the exception.
If you use the form:
function sum1() {...}
Then, the symbol sum1
is defined at parse time BEFORE any code executes so the order of placement in the file is not an issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With