This scene is actually a direct reference to the scene from The Great Train Robbery where a similar scene concludes the movie.
Here in this below video at 0:25 secs Martin Scorsese himself mentions the very film and says "...that's why I had Joe Pesci shoot at the camera"
Youtube Link
You can also find the mention of the same connection in here
In an interview with the American Film Institute, Scorsese explains
the connection between his movie and Porter's: "Basically, in
Goodfellas, it's a bunch of outlaws who do this incredible robbery.
And then they all kill each other, and the police get them at the end.
It's exactly the same story." In other words, Scorsese ripped off the
scene. But, you know what they say—imitation is the sincerest form of
flattery.
Here, by "Porter" he means Edwin S. Porter