0

I am trying to return the length of a linked object(list). However, the function I wrote doesn't return anything.

let linkedObject = { value: 1, rest: { value: 2, rest: { value: 3, rest: null } } }

function countDepth(liste, count = 0){
        if (liste == null) return count
        else {
            count ++
            liste = liste.rest
            countDepth(liste, count)
    } 
}

console.log(countDepth(linkedObject))```

expected output:
'3'
actual output:
'undefined'

1 Answer 1

1

You need to return the recursive call:

return countDepth(liste, count);

Also note it can be optimized and made more concise like so:

const countDepth = (l, c = 0) => !l ? c : countDepth(l.rest, ++c);
Sign up to request clarification or add additional context in comments.

3 Comments

This worked, but you can explain why for future reference?
Because if the if statement isn't fulfilled, there are no returns within that execution of the function, so undefined is returned.
Ohh..I think that makes sense. The first iteration returns the second iteration, which returns the third and so on...all the way to the actual answer. Without the second return statement, this chain would be broken and the actual answer would be left abandoned.

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.