Functional-Light JavaScript, v3

Recursion Exercise

Kyle Simpson

Kyle Simpson

You Don't Know JS
Functional-Light JavaScript, v3

Check out a free preview of the full Functional-Light JavaScript, v3 course

The "Recursion Exercise" Lesson is part of the full, Functional-Light JavaScript, v3 course featured in this preview video. Here's what you'd learn in this lesson:

Kyle instructs students to define a palindrome checker using recursion.


Transcript from the "Recursion Exercise" Lesson

>> Kyle Simpson: Okay, let's try out an exercise to practice this whole idea of recursion. In this exercise, you're gonna be writing a palindrome checker. If you don't know what palindromes are, this is one of those classic interview questions. A palindrome is a string that reads exactly the same forwards and backwards.

So for example, abcba, if you reverse that, it's still gonna say abcba. Okay, so that is a palindrome. There's a couple of base cases, by the way. An empty string is a palindrome, and a single character is also a palindrome, because it reads in both directions. Also we should point out that both the string aba and the string abba, both of those are palindromes, because in both cases, they read the same backwards and forwards, okay.

Now there's a very straightforward way of solving this problem iteratively. And there's a good chance on some interview question somewhere that somebody's gonna have asked you, implement it iteratively. But because we're talking about recursion, we wanna move beyond the iterative approach, where we just simply go through all of the characters one at a time.

We wanna move beyond the iterative approach and try to think about it recursively. I'm not gonna tell you exactly how to do it, but there is a hint here that points at exactly the right way to think about palindromes in a recursive sense. So I want you to make sure you read that hint as you tackle this exercise.

If you look in the exercise, there's an isPalindrome function that you need to fill out the definition of, it should be recursive. And also, there's a set of test cases down here at the bottom, and all of these should end up printing out true. So make sure you test your isPalindrome function with these particular test cases.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now