Be Careful What You console.log

I caught myself out.

What’s worse – I thought I was helping myself in doing so!

Let me set the scene:

I have a project where I need to find the most recent file in a directory.

There’s probably a hundred or more ways to do this, but my way – in this instance – goes a little something like this:

It’s a node JS project btw.

Each of the files in the directory would be in the format {timestamp}.csv .

There exists a possibility that the files may be restored from backup, therefore I couldn’t rely on the “created at” dates.

Anyway, this all works quite well.

The directory contents during test looks something like this:

And here’s the contents of the  findMostRecentFileInList  function:

Full marks if you have already spotted the problem.

If not, no worries, allow me to explain.

We can disregard the vast majority of this function and just focus on two lines:

What was confusing the heck out of me was that in the next  then statement, the value I would receive would be incorrect. Yet the console log output only one step prior was definitely right.

Welp, the reason is as amusing as it is frustrating. It’s exactly the sort of thing that catches out many a developer (I would bet).

What happens here is that by calling  list.reverse() in the console log statement, the list is correctly reversed.

The slice function takes the value I need and that’s correctly output to the screen.

So far, so good.

Then, on the very next line, I take the reversed list and reverse it again… putting it back into the original order. Then take a slice from that, and return that instead.


It’s so obvious when it’s spelled out to you, but debugging that sort of thing is how devs like me lose tens of minutes, if not hours of time.

These sorts of things tend to catch me out late at night. Maybe I should work earlier in the mornings.


Published by

Code Review

Code Review

CodeReviewVideos is a video training site helping software developers learn Symfony faster and easier.

2 thoughts on “Be Careful What You console.log”

    1. TDD would have caught this problem for sure. The reason I am not doing TDD on this project is it’s a learning exercise. I’m testing Rabbit MQ with various different languages, all talking to each other.

      But I agree with your sentiment 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *