PDA

View Full Version : Syntax Question



Trinithis
07-17-2007, 05:58 PM
Despite having semicolons optional in JS, I like to use them whenever appropriate anyway. That being the case, I'm not sure if the following deserve semicolons (because they end in braces):



var a = function() {
return 5;
}




var b = {
b: 5,
c: 3
}


Or is the answer more a coding preference?

DimX
07-17-2007, 06:32 PM
They do, they are simple variable assigments, so if

var i = 0;
needs a semicolon, then

var i = function() { return 0; };
needs it as well.

Automatic semicolon insertion is done at that place anyway.

jscheuer1
07-17-2007, 06:37 PM
You really answered your own question, it is a preference. However, if any line that has ended deserves a semi-colon, these do. There are cases where adding a semi-colon after a closing brace will mess things up (at least I think I have seen this), but these are not examples of that.

I generally try to get all the semicolons in when coding, and it is good form. They are only required when the meaning could be ambiguous to the script parser. They cannot be used if the end of a statement is not appropriate at that point.

Trinithis
07-17-2007, 06:43 PM
Alright, thanks for both your replies. I just wasn't sure because I've seen it done both ways, but yeah, the more I think of it, it does make sense to have them there. I suppose a good splash test is to see whether or not the code works if you don't use line breaks at the end of any statement.

(Oh, just a random question, how many posts does it take to get an avatar? Thought it was 150 posts.)

jscheuer1
07-17-2007, 09:33 PM
Alright, thanks for both your replies. I just wasn't sure because I've seen it done both ways, but yeah, the more I think of it, it does make sense to have them there. I suppose a good splash test is to see whether or not the code works if you don't use line breaks at the end of any statement.

(Oh, just a random question, how many posts does it take to get an avatar? Thought it was 150 posts.)

Yeah, taking out the line breaks is the acid test.

I think ddadmin is the only one who knows for sure what the post requirement for avatars is currently set at. I have mod privileges, but I cannot even see, let alone edit the screen where that information is stored.

Twey
07-17-2007, 10:37 PM
They are only required when the meaning could be ambiguous to the script parser.However, those cases are more widespread than the beginner might expect. For example:
var a = 1, b = a
(a + b) * 3... will break: the interpreter attempts to parse it as:
var a = 1, b = a(a + b) * 3;since this is valid.