Reputation: 495
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
Upvotes: 0
Views: 72
Reputation: 135367
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'
Upvotes: 2
Reputation: 68413
However, I don't really get what exactly if (!list) {} does.
It checks if list
variable still has a value which is other than falsey value such as null
, undefined
, 0
, false
, NaN
, ""
or ''
. If the list has any falsey value, then it returns undefined
.
Why is it true, if list has an element n?
As per the link you have shared, value of list is
var list = {
value: 1,
rest: {
value: 2,
rest: {
value: 3,
rest: null
}
}
};
which means either rest
has child elements or it has null
.
eventually, it will have null
which is what this condition will assert and return undefined
.
Upvotes: 0