1

I'm trying to become more familiar with callback functions in Javascript. I've created a simple app to push a new member to a development team array. I'm trying to use the addDev function as my callback practice. I'm receiving an error: Uncaught TypeError: addDev is not a function.

var devTeam = [];

function devMember(fName, lName, addDev){
    this.firstName = fName;
    this.lastName = lName;
    this.fullName = firstName + " " + lastName;
    addDev(fullName);
}

function addDev(member){
    devTeam.push(member);
    console.log(devTeam);
}

devMember('Jay', 'Spears');
2
  • 2
    You're not passing the callback function; you're just passing the names. Your devMember() function takes 3 arguments. Commented Sep 23, 2015 at 15:41
  • devMember should have 3 parameters Commented Sep 23, 2015 at 15:42

1 Answer 1

5

That's because you never passed addDev to devMember.

Try devMember('Jay', 'Spears', addDev);

Even though addDev is defined (hoisted), because you're calling the third argument to devMember also addDev, you're overriding it. And then you don't pass anything as a third argument when you invoke devMember('Jay', 'Spears'), so it is undefined in the execution context of devMember.

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

6 Comments

addDev is global function, shouldn't it be called?
@Tushar No, because the addDev declaration in the function arguments shadows the global declaration, and the variable will be undefined if no third parameter is passed. The code would have worked without this third parameter.
@JoshSpears yep, if you remove that third parameter from devMember, or even call it something else (either way, not recommended), it would work. The best thing is to call it something other than addDev, and then pass addDev as an argument when you invoke devMember.
@caasjj I renamed addDev to a proper name. function devMember(fName, lName, pushMember){};
That'll do it, as long as you remember to pass in addDev when you invoke devMember.
|

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.