× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How to Perform Recursion in JavaScript with an Immediately Invoked Function Expression (IIFE)

Michael Perrenoud
Mar 06, 2015
<p>So before I get into the code proposed in the subject, let's review a typical example of recursion. Let's assume we have the following data structure:</p> <pre><code class="language-javascript">var data = [{ name: 'Name 1', value: 'Value 1', items: [{ name: 'Name 1a', value: 'Value 1a' }, { name: 'Name 1b', value: 'Value 1b' }] }, { name: 'Name 2', value: 'Value 2' }, { name: 'Name 3', value: 'Value 3', items: [{ name: 'Name 3a', value: 'Value 3a' }, { name: 'Name 3b', value: 'Value 3b' }] }]; </code></pre> <p>A common way to recurse that structure and print the values to the <code>console</code> would be like this:</p> <pre><code class="language-javascript">printItems(data); function printItems(items) { if (!items) { return; } for (var i = 0; i &lt; items.length; i++) { var item = items[i]; console.log(item.name + ' - ' + item.value); printItems(item.items); } }</code></pre> <p>Now while there's <strong>nothing </strong><em>fundamentally wrong with this</em>, if you have a lot of recursive functions that end up strung together in your workflow it can get really hard to keep context when debugging and reading the code. That's where the IIFE comes in!</p> <p>What if we did something like this?</p> <pre><code class="language-javascript">(function printItems(items) { if (!items) { return; } for (var i = 0; i &lt; items.length; i++) { var item = items[i]; console.log(item.name + ' - ' + item.value); printItems(item.items); } })(data);</code></pre> <p>While it doesn't seem significantly different, when strung together in a huge workflow, not having to search for that function can be so helpful! The key is that the <code>function</code> is a <strong>named function</strong>.</p> <p>Along the same lines, I hope this hint has been helpful as well.</p> <p>Happy coding!</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus