Stupid Web Tricks: Name Checker (Recursion Example)

Here's a simple example of recursion in JavaScript: adding uniquely named items to an unordered list. Type a name in the "name" field. Try a name that's already taken. Note how the duplicated name gets appended with numbers. Jump for joy.

Add a name

A web designer friend had asked me about recursion, and wondered why it's so darned important.

If we asked the CS heads around us at the time, it was likely we'd hear a monologue about computing factorials, writing Fibonacci sequences, or traversing node trees. Since I was already on a project that required this kind of behavior, it was worth writing an example more relevant to web development. It also turned out to be more polite than directing him to Wikipedia while repeatedly yelling RTFM.

Ok, so the way it works is this:

  1. Get a list of existing names
  2. Compare the new name against list of names
  3. If the name is already taken, change it a bit, go back to first step to check the change
  4. If the name isn't taken, then go ahead and return the value

Presence of the last step makes the algorithm recursive. Remove it, and you get an infinite loop; under some circumstances, your computer may run out of memory. Some systems barf out an error and say "too much recursion," even though it really means "i don't think this is recursive at all.... I give up."

Link to function: checkNewName.