Understanding Recursion in JavaScript

Zak Frisch
Nov 28, 2016 · 4 min read

What is recursion?

Recursion — relating to or involving a program or routine of which a part requires the application of the whole, so that its explicit interpretation requires in general many successive executions.”

function demo() {
demo();
}
demo();

example 2 recursion
function countDown(n) {
console.log(n);
if(n >= 1) countDown(n-1);
}
countDown(5);
function countDown(n) {
for(let i=n; i >=0;i--) {
console.log(i);
}
}
countDown(5);

function Traverse(ele, callback) {
callback(ele);
ele = ele.firstChild;
while (ele) {
Traverse(ele, callback);
ele = ele.nextSibling;
}
}
Traverse the DOM Example
Traverse Upwards Example
function TraverseUp(ele, callback) {
callback(ele);
ele = ele.parentNode;
while (ele) {
TraverseUp(ele, callback);
ele = ele.prevSibling;
}
}
TraverseUp(document.getElementById('outer'), (ele) => console.log(ele));


Zak Frisch

Written by

Passionate Web and Software Developer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade