4

I met with some strange, in my opinion, behaviour. I think I don't understand what is going on, so if anyone can help me with this ... I will be glad.

function dateString1(date) {
return (
    ('0' + date.getDate()).slice(-2) + '/' +
    ('0' + (date.getMonth()+1)).slice(-2) + '/' +
    date.getFullYear()
);
}


function dateString2(date) {
return 
    ('0' + date.getDate()).slice(-2) + '/' +
    ('0' + (date.getMonth()+1)).slice(-2) + '/' +
    date.getFullYear()
;
}

so, dateString1 will return the string I'm looking for, but dateString2 will return undefined. Checked it on Chrome and IE8.

What's going on?

Thanks

David
  • 2,830
  • 6
  • 22
  • 29

1 Answers1

10

Putting anything on a new line in JS is a stupid idea, for this very reason. Automatic semi-colon insertion is killing your code, return; is how the JS engine will interpret your code (which by itself is a valid statement). Put it like this:

function dateString2(date) {
    return ('0' + date.getDate()).slice(-2) + '/' +
    ('0' + (date.getMonth()+1)).slice(-2) + '/' +
    date.getFullYear();
}

Stay away from things like this:

if (something)
{
    // logic
}

And always use this style:

if (something) {
    // logic
}
Todd Motto
  • 913
  • 6
  • 10
  • Is there a way to disable ASI? I guess that "use strict"; is not enough. – Silviu Burcea Jan 20 '14 at 12:09
  • 2
    The second part of your answer has nothing to do with the question, and is subjective (I personally like your proposed style, but others swear by [K&R](http://en.wikipedia.org/wiki/1_true_brace_style#K.26R_style), there is no technical reason to prefer the one over the other). – Rob W Jan 20 '14 at 12:09
  • @SilviuBurcea ASI is a language feature, you cannot disable it. You can use [JSHint](http://www.jshint.com/) to scan code for potential errors though (either via the web interface, command-line tool or integrated in your text editor). – Rob W Jan 20 '14 at 12:11
  • @RobW I know about JSHint, I just don't like ASI, people are that lazy to not type a ; where is needed. This is just sad because they added ASI instead of developers education. – Silviu Burcea Jan 20 '14 at 12:16
  • @RobW Nothing wrong with giving advice. There is a technical reason to use one syntax over the other if one style causes errors in places if the user doesn't understand the difference. @Silviu, `use strict` enables strict mode which has nothing to do with ASI, more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode – Todd Motto Jan 20 '14 at 13:11