1

I've got this really annoying issue where a function returning a value of undefined every time even though the console.log() always shows that there is a value when getting into the first if statement

This is my function

function getElementIdentifier(elem, domSelector) {
    if(elem.getAttribute('id') !== null) {
        console.log('here');

        return elem.id + ' ' + domSelector;
    } else {
        getElementIdentifier(elem.parentNode, elem.tagName + ' ' + domSelector);
    }
}

This is how I call it

getElementIdentifier(elem, '');

Heres a fiddle to replicate it. http://jsfiddle.net/wqCSn/5/ (thanks @adeneo)

10
  • 1
    you miss return state in second branch and you check elem.getAttribute('id') but try to return elem.id -- do next return '' + elem.id + ' ' + domSelector; Commented Mar 15, 2014 at 15:15
  • Seems to work just fine -> jsfiddle.net/wqCSn Commented Mar 15, 2014 at 15:17
  • @null elem is incoming parametr Commented Mar 15, 2014 at 15:17
  • @VasilVanchuk I'm calling itself so dont need a return this. Commented Mar 15, 2014 at 15:18
  • 1
    Why would it return the result when it's recursive, it returns something if the condition is met on the next iteration. Commented Mar 15, 2014 at 15:23

2 Answers 2

3

Your function does not return value if call self recursively. You should to add return statement ro alternative branch of algorithm

function getElementIdentifier(elem, domSelector) {
    if(elem.getAttribute('id') !== null) {
        return elem.id + ' ' + domSelector;
    } else {
        return getElementIdentifier(elem.parentNode, elem.tagName + ' ' + domSelector);
    }
} 
Sign up to request clarification or add additional context in comments.

Comments

1

hmmmm... try this:

function getElementIdentifier(elem, domSelector) {
 if(elem.getAttribute('id') !== null) {
    console.log('here');

    return elem.id + ' ' + domSelector;
 } else {
 //return the recursion returned value (sounds like inception) but
 //you are expecting a value from this function... 
    return getElementIdentifier(elem.parentNode, elem.tagName + ' ' + domSelector);
 }
}  

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.