3

perennial newbie question: how do i fix this "not a function" error:

exports.height = (input) => {
    function height(node, height) {
        if (node.left) {
            if (height > maxHeight) {
                maxHeight = height;
            }
            **height(node.left, height+1); // <-- Says "Not a function"**
        }
    }

    var maxHeight = 0;
    height( input, 0 ); // <--- This works fine.

    return maxHeight;
}

says, TypeError: height is not a function

  at height (BinarySearchTree.js:53:5)

Thanks! Nilesh

3
  • just change that to exports.height ,it should work Commented Nov 2, 2016 at 18:09
  • You named your parameter the same as the function. Did you try debugging with console.log(height)? Commented Nov 2, 2016 at 18:10
  • @Geeky: exports.height is referencing a different function. There are too many things named height in this code. Commented Nov 2, 2016 at 18:12

2 Answers 2

3

You accidentally shadowed your height variable

function height(node, height) {
    if (node.left) {
        if (height > maxHeight) {
            maxHeight = height;
        }
        height(node.left, height+1);
    }
}

var maxHeight = 0;
height( input, 0 ); // 0 is obviously not a function ^_^

Try renaming the height parameter to something like h

function height(node, h) {
    if (node.left) {
        if (h > maxHeight) {
            maxHeight = h;
        }
        return height(node.left, h+1); // don't forget your return
    }
}

var maxHeight = 0;
height( input, 0 );

All that said, you might want to reconsider your function alltogether

function height (node) {
  if (node === undefined)
    return -1;
  else
    return Math.max(height(node.left), height(node.right)) + 1;
}
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is you've shadowed the function variable named height with an argument of the same name:

function height(node, height) {

Because JavaScript functions are first-class citizens, in the context of the height function body, there is now a local variable named height which is not the same as the function.

Consider changing the name of one of them, like so:

function height(node, h) {
    if (node.left) {
        if (h > maxHeight) {
            maxHeight = h;
        }
        height(node.left, h+1);
    }
}

Comments

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.