Accio Recursion!: Your New Favorite JavaScript Spell

We printed the first three values successfully, but once our function reached the nested values, it stopped console.log’ing what we wanted it to.Looks like we need to go a bit deeper.What if we try this deeperButNotGreatIterator function?If we walk through what this function is doing, we see that it’s iterating through each key of the targetObject and checks to see if the value that key points to is typeof object..If it is, it goes one level deeper and iterates over that object to console.log its values..That sounds like it might give us what we’re looking for..Let’s give it a try by running deeperButNotGreatIterator(harryPotter):Close, but no Pepper Imp.Once again, when we reached the nested values, we didn’t get the output we wanted..BUT, we did get one level deeper than last time by printing each individual object contained within the arrays that the friends and organizations keys point to.We could add another iteration to our function to get us one level deeper, however, let’s think about how scalable that is..The purpose of writing a function, and furthermore a function with argument(s), is so it can be reused for any argument passed in..This means that, with our current implementation, we would need to know the exact format of the targetObject, and we could potentially end up with a very unwieldy function depending on how many nested objects the targetObject has.If only there was a way for us to have our function traverse through any depth and number of nested objects…Accio recursion!RecursionA recursive function is a function which calls itself.With recursion, we can write this short, concise function which will return all the primitive values within the targetObject regardless of how far nested they are!Let’s try to dissect what this recursiveIterator function is doing..We pass in a targetObject, and if that targetObject is typeof object, we’re going to iterate through each of its keys and pass its value as the argument to — wait for it — the recursiveIterator function!And that cycle continues until the value we reach is not typeof object, in which case our else statement will execute and we will console.log the value.Let’s check the output of running recursiveIterator(harryPotter):We did it!To conclude, recursion is a powerful tool for traversing nested data structures..It allows you to keep your code DRY, concise, and scalable..Our recursiveIterator function does exactly what we wanted it to, and it’s nearly as simple as casting “Accio primitive values of harryPotter object!”. More details

Leave a Reply