user548470 user548470 - 4 months ago 15
Javascript Question

JavaScript: Checking a list for elements

I'm currently learning JavaScript using Marijn Haverbekes excellent book "Eloquent JavaScript". Now there is this exercise where you have to write a recursive function that returns the nth element of a nested list. If there is no such element, the function is supposed to return

undefined
. The solution looks like this:

function nth(list, n) {
if (!list)
return undefined;
else if (n == 0)
return list.value;
else
return nth(list.rest, n - 1);
}


So far, everything seems pretty clear to me. However, I don't really get what exactly
if (!list) {}
does. How exactly does this condition evaluate? Why is it true, if
list
has an element
n
?

The complete excercise can be found here:
http://eloquentjavascript.net/04_data.html#p_7AnSuS26HF

Answer

This

if (!list)

Is a shorthand way of saying

if (list === false || list === 0 || list === '' || list === null || list === undefined || list !== list /* NaN */) ...

!list will happen in when the list is shorter than n elements.

// 4 is larger than the list length here, (2)
// !list will happen
nth({value: 'a', rest: {value: 'b', rest: null}}, 4)
//=> undefined

// 1 is not larger than the list length
// !list will not happen
// instead, n === 0 happens after recursing 1 time
nth({value: 'a', rest: {value: 'b', rest: null}}, 1)
//=> 'b'
Comments