4

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?

1
  • 1
    Function declarations are hoisted, function expressions are not. Commented Dec 2, 2015 at 4:19

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

Comments

3

You have to define sum1 prior to calling it, or use a function declaration:

// Define first:
var sum1 = function (a,b, callback){
    callback(a + b);
};
sum1(1, 2, function(sum) {
    console.log(3 + sum);
});

Or

// Function Declaration:
sum1(1, 2, function(sum) {
    console.log(3 + sum);
});
function sum1(a,b, callback){
    callback(a + b);
};

Function declarations can be after the code calling it. However, for clarity's sake, you should always define a function (either way) before you use it in your code.

Comments

1
sum1 = function (a,b, callback){
  callback(a + b);
};

This is a function expression , so you can't call sum1() before it's definition , move it above the function call.

Comments

0

Check if it is not in scope.. it's reference might need to be passed.. I had a similar issue in Protractor, so I had to pass the function reference and bingo it worked for me.. ;)

1 Comment

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.