As far as I can tell, in this case, the two questions weren't of such good quality: the older one could also have been closed as a "simple typographical error", but it's good to see that it was correctly solved anyway. In the second question, the OP was trying to achieve the same exact result, but their issue was a bit different.
The problem here is: should we close questions as duplicates even if the particular issue to achieve the same result is different? Well, Stack Overflow's main purpose is to create an online Q&A archive of solved questions so that future users (and hopefully whoever searches the web) will be able to find them and quickly solve their problems. Now put yourself in the shoes of a regular user searching for a way to find the longest word in a phrase, like these two questions are asking: you will obviously search the web for something along the line of "find longest word in a sentence javascript". Then there are two possible scenarios:
We didn't close the other questions concerning the same purpose because of their little coding (and related issues) differences: you'll then find a bunch of similar questions, getting confused looking for the one which fits your needs.
We closed the other questions as duplicates, and you'll easily find the only (original) one without any trouble.
In my honest opinion, we don't actually want (nor need) the first scenario to happen. Instead, our goal should be to provide the best solution to the problem, and close any other following question about the same issue as a duplicate of the well answered older one. The newer question should then be rephrased to represent a different (and not duplicated) issue: there's still chance for someone to search something like "infinite for loop javascript issue".
In conclusion, as said by Anthony Grist: the key point is that people coming from Google (or anywhere else) don't actually care which problem somebody else faced while trying to achieve the same goal.
Notes
This hasn't got to be taken as "the holy guideline" in any case. It's clear that there are infinite possibilities when talking about duplicated answers, and it's complicated to find an unique solution for all of them, but common sense can solve anything, and there's always the option of drawing moderators' attention in edge cases.