user548470 user548470 - 1 year ago 64
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

. The solution looks like this:

function nth(list, n) {
if (!list)
return undefined;
else if (n == 0)
return list.value;
return nth(, 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
has an element

The complete excercise can be found here:

Answer Source


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'