Code Painters The Art of Coding


The weirdest programming language feature ever

I have to admit I had a long break from web applications development, and the topic changed a lot over the last few years. As I'm developing a web app now, I decided to improve my JavaScript knowledge, just to learn about an exceptionally awkward language feature.

In JavaScript, each statement can be terminated with a semicolon. If it is not, the semicolon is inserted automatically by the language implementation (the exact rules are irrelevant here, you can easily find it). Sounds innocent at first, but it is actually quite dangerous. Let's say we want to return an array from a function:

function a()
    return [ 'a' ]
print (a());

The result matches our expectations:

czajnik@lapcio:~$ rhino a.js

Now let's insert a new line after the return statement:

function b() 
    [ 'b' ]
print (b());

This snippet produces the following output:

czajnik@lapcio:~$ rhino b.js

That's because a semicolon was inserted automatically after return, and the array alone on the next line is acceptable syntax (in JavaScript an expression alone is a valid statement). This is weird, pathetic and scary...

  • Facebook
  • Digg
  • Twitter
  • LinkedIn
  • Google Bookmarks
  • Reddit
  • StumbleUpon
Comments (0) Trackbacks (0)

No comments yet.

Leave a comment

No trackbacks yet.