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

18 October 2010   0 comments   Javascript

Mind That Age!

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

Powered by Fusion×

I had a piece of code that looked like this:

function add_to_form(f, all_day) {
  console.log(all_day);
  if (all_day)
    $('input[name="all_day"]', f).val('1');
  else;
    $('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:

true
(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.

Comments

Thank you for posting a comment

Your email will never ever be published


Related posts

Previous:
My tricks for using AsyncHTTPClient in Tornado 13 October 2010
Next:
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:
Don't that this or bind 12 April 2016
How to "onchange" in ReactJS 21 October 2015
Javascript tip: nifty use of the console.log function in Firebug 07 November 2010
slim, a new free web service for white space optimisation 25 July 2006
To then() or to success() in AngularJS 27 November 2014