Noob alert! I can't seem to understand the logic inside this while loop. It is taken from O'Reilly's "JavaScript: The definitive Guide" Chapter 15.3, example 15-2. I understand that it is decrementing n with n--. But I can't understand the reasoning or theory behind it with the boolean AND operator. What is this loop saying? While n is decremented and var e exists? To me, it seems like it should be incrementing, but when I changed the -- to ++ the function always returns null. Help me to understand deeper.
var firstpara = document.getElementsByTagName("p")[0];
/**
* Return the nth ancestor of e, or null if there is no such ancestor
* or if that ancestor is not an Element (a Document or DocumentFragment e.g.).
* If n is 0 return e itself. If n is 1 (or
* omitted) return the parent. If n is 2, return the grandparent, etc.
*/
function parent(e, n) {
if (n === undefined) n = 1;
while (n-- && e) e = e.parentNode;
if (!e || e.nodeType !== 1) return null;
return e;
}
parent(firstpara, 1); //returns <body>...</body> which is the parent node in my testpage
n--will betrueunlessnis zero, so the loop stops when eithernhas been decremented to zero or when there's no parent after some number of iterations.