Nasty JavaScript wart (or rather, don't take shortcuts)

18 October 2010   0 comments   Javascript

Mind That Age!

This blog post is 8 years old! Most likely, its content is outdated. Especially if it's technical.

I had a piece of code that looked like this:

function add_to_form(f, all_day) {
  if (all_day)
    $('input[name="all_day"]', f).val('1');
    $('input[name="all_day"]', f).val('');
  console.log($('input[name="all_day"]', f).val(''));
  return f; 

When I ran it, the console output was this:

(an empty string)

What had happened was that I had accidentally put a semi-colon after the else statement. Accidentally as in stumbled on the keyboard. I didn't spot it because semi-colons are so common in JavaScript that you sort of go blind to them.

The wart was that it didn't cause a syntax error. IMHO it should have because you'd expect there to always be something happening after the else.

So instead of using the shortcut notation for if statements I've decided to write it out in full instead:

function add_to_form(f, all_day) {
  if (all_day) {
     $('input[name="all_day"]', f).val('1');
  } else {
     $('input[name="all_day"]', f).val('');
  return f; 

Optimizers like Google Closure will do a much better job optimizing the code than I ever will anyway.


Your email will never ever be published

Related posts

My tricks for using AsyncHTTPClient in Tornado 13 October 2010
Why I gave up on JQuery UI's autocomplete 20 October 2010
Related by Keyword:
Use closure for your Django context processors 09 May 2015
Comparing Google Closure with UglifyJS 10 July 2011
The awesomest way possible to serve your static stuff in Django with Nginx 24 March 2010
IssueTrackerProduct 0.7 released 16 December 2005
Gmail shortcuts 26 April 2005
Related by Text:
Be very careful with your add_header in Nginx! You might make your site insecure 11 February 2018
jQuery and Highslide JS 08 January 2008
I'm back! has been renewed 05 June 2005
Anti-McCain propaganda videos 12 August 2008
I'm Prolog 01 May 2007