Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return with parentheses and without gets different results [duplicate]

Tags:

javascript

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

like image 316
David Avatar asked Dec 25 '22 14:12

David


1 Answers

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
}
like image 198
Todd Motto Avatar answered Dec 28 '22 06:12

Todd Motto