tags:

views:

1183

answers:

12

The following code illustrates an object literal being assigned, but with no semicolon afterwards:

var literal = {
    say: function(msg) { alert(msg); }
}
literal.say("hello world!");

This appears to be legal, and doesn't issue a warning (at least in FireFox 3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed? I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it.

+14  A: 

Not technically, JavaScript has semicolons as optional.

But, as a general rule, use them at the end of any statement. Why? Because if you ever want to compress the script, it will save you from countless hours of frustration.


@Kamiel: Incorrect - semicolons are optional, and his JavaScript is valid. However, that doesn't mean it is a Good Thing.

@Geoff: The question posted is "Are semicolons needed after an object literal assignment in JavaScript?" - your "answer" doesn't really answer the question. That may be why you were voted down. It isn't that JSLint isn't useful (depending on your opinion of Crockford's assessment of the language's strengths and weaknesses), but it didn't really answer the question.

@TonyLa: I don't think I was being arrogant, but thanks for the observation; I think I am being helpful. As for your "correction," semicolons in JavaScript that humans create are, for all intents and purposes, optional. Automatic semicolon insertion is performed by the interpreter, so the poster of the original question can leave them out if he so chooses. You said "Semicolons are not optional with statements like break/continue/throw" - wrong again. They are optional - what is really happening is that line terminators affect the automatic semicolon insertion; it is a subtle difference. Regardless, I didn't think a full discussion of the standard is what the original poster was after, so I didn't feel it necessary to go into all of the details in my answer.

@TonyLa: You crack me up - why are you still fighting this battle? More importantly, why don't you quote the remainder of that portion of the standard? Here is the rest of it:

For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.

The fact is, what I said remains true:

...semicolons in JavaScript that humans create are, for all intents and purposes, optional.

Arguing about the particulars of the spec is worthless at this point, because you see it your way and I see it mine. By the way, the word "may" in the part you quote has a particular definition in English, maybe you should look it up. If it said "such semicolons must always appear explicitly in the source text," your point would be stronger.

Jason Bunting
This answer is wrong. The specification states: "semicolons may be omitted from the source text in certain situations" and that has significantly different meaning than "JavaScript has semicolons as optional."
Garrett
@Garrett: Your comment is appreciated. The question is "Are semicolons needed after an object literal assignment in JavaScript?" In that exact case, the answer, if you want to follow the spec, is always "no," as far as I can tell. Regardless of what you place into an object literal, would you really ever need an explicit semicolon? Off of the top of my head, I would say no.Regardless, I appreciate the disagreement with my answer, I should have chosen my initial words more carefully. Especially with respect to my comments to @TonyLa, I think I explain things well enough.
Jason Bunting
@Jason, your comment is wrong. If the object literal were followed by a LineTerminator followed by `[]`, the `[]` would be parsed as property accessor, not as ArrayLiteral. TonyLa already pointed you to the spec; I suggest you read it before continuing with this discussion.http://jibbering.com/faq/notes/code-guidelines/#asi
Garrett
A: 

Use JSLint to keep your javascript clean and tidy

JSLint says:

Error:

Implied global: alert 2

Problem at line 3 character 2: Missing semicolon.

}

Edit: Why the vote down? JSLint is the closest thing there is to a "strict" javascript style guide

Edit 2: @JasonBunting thanks for explanation. I guess I didn't phrase my answer properly. whoever it was undid the vote down, so thanks! I tried to post fast instead of posting quality.

Geoff
The problem with JSLint is that it was written by Douglas Crockford who believes that semi-colons should be mandatory. Thus the alert.
staticsan
@staticsan - It's not just a personal belief. Requiring semi-colons at the end of every line means that the js file can be minified into a single line file.
Geoff
A: 

This is not valid (see clarification below) Javascript, since the assignment is just a regular statement, no different from

var foo = "bar";

The semicolon can be left out since Javascript interpreters attempt to add a semicolon to fix syntax errors, but this is an extra and unnecessary step. I don't know of any strict mode, but I do know that automated parsers or compressors / obfuscators need that semicolon.

If you want to be writing correct Javascript, write the semicolon :-)

EDIT: According to the ECMAscript spec, http://www.ecma-international.org/publications/standards/Ecma-262.htm, the semicolons are automatically inserted if missing. This makes them not required for the script author, but it implies they are required for the interpreter. This means the answer to the original question is 'No', they are not required when writing a script, but, as is pointed out by others, it is recommended for various reasons.

Kamiel Wanrooij
+1  A: 

Javascript actually does not require semicolons if you are putting each statement on its own line.

Most people ignore this, however, because semicolons are just good practice. They make your statements unambiguous. Nobody is confused as to exactly what you mean.

Josh Hinman
There are ambiguous cases that require semicolons even when the statements are on different lines.
Ates Goral
A: 

Semi-colons are optional, but your code will become invalid if you run it through a JavaScript minimizer such as the YUI Compressor. Therefore, its a good practice to always include semi-colons.

Ricky
+2  A: 

The semi-colon is not necessary. Some people choose to follow the convention of always terminating with a semi-colon instead of allowing Javascript to do so automatically at linebreaks, but I'm sure you'll find groups advocating either direction.

If you are looking at writing "correct" Javascript, I would suggest testing things in Firefox with javascript.options.strict (accessed via about:config) set to true. It might not catch everything, but it should help you ensure your JavaScript is more compliant.

EDIT: @JasonBunting The folks answering late are just unlikely to get voted up. For my part, I got a phone call in the middle of answering the question so the post ended up coming through later than it might have otherwise. And there doesn't seem to be a feature that notifies you of answers came through between starting a answer and posting it before it actually submitted.

Travis
+3  A: 

YUI Compressor and dojo shrinksafe should work perfectly fine without semicolons since they're based on a full javascript parser. But Packer and JSMin won't.

The other reason to always use semi-colons at the end of statements is that occasionally you can accidentally combine two statements to create something very different. For example, if you follow the statement with the common technique to create a scope using a closure:

var literal = {
    say: function(msg) { alert(msg); }
}
(function() {
    // ....
})();

The parser might interpret the brackets as a function call, here causing a type error but in other circumstances it could cause a subtle bug that's tricky to trace. Another interesting mishap is if the next statement starts with a regular expression, the parser might think the first forward slash is a division symbol.

Daniel James
I recently ran into a similar issue (again due to a closure following an assignment). This is a very likely scenario and is a good argument for consistent usage of semicolons. +1
Ates Goral
+2  A: 

@JasonBunting Try to be less arrogant and more helpful because you never know when you might be wrong ;)

In this case there is no need for a semicolon at the end of the statement. The conclusion is the same but the reasoning is way off.
Javascript does not have semicolons as "optional". Rather it has strict rules around automatic semicolon insertion. Semicolons are not optional with statements like break/continue/throw. Refer to ECMA Language Specification for more details http://www.ecma-international.org/publications/standards/Ecma-262.htm

TonyLa
The only correct answer so far.
Garrett
+2  A: 

Javascript interpreters do something called "semicolon insertion", so if a line without a semicolon is valid, a semicolon will quietly be added to the end of the statement and no error will occur.

var foo = 'bar'
// Valid, foo now contains 'bar'
var bas = 
    { prop: 'yay!' }
// Valid, bas now contains object with property 'prop' containing 'yay!'
var zeb = 
switch (zeb) {
  ...
// Invalid, because the lines following 'var zeb =' aren't an assignable value

Not too complicated and at least an error gets thrown when something is clearly not right. But there are cases where an error is not thrown but the statements are not executed as intended due to semicolon insertion. Consider a function that is supposed to return an object:

return {
    prop: 'yay!'
}
// The object literal gets returned as expected and all is well
return
{
    prop: 'nay!'
}
// Oops! return by itself is a perfectly valid statement, so a semicolon 
// is inserted and undefined is unexpectedly returned, rather than the object 
// literal. Note that no error occurred.

Bugs like this can be maddeningly difficult to hunt down and while you can't ensure this never happens (since there's no way I know of to turn off semicolon insertion), these sorts of bugs are easier to identify when you make your intentions clear by consistently using semicolons. That and explicitly adding semicolons is generally considered good style.

I was first made aware of this insidious little possibility when reading Douglas Crockford's superb and succinct book "Javascript: The Good Parts". I highly recommend it.

JesDaw
A: 

I'm pretty sure that will break on IE. While it may be valid javascript, you probably have to add the semicolon because of that anyway

Orion Edwards
A: 

@JasonBunting

Again you are wrong. Taken from the ECMA spec

Certain ECMAScript statements (empty statement, variable statement, expression statement, do-while statement, continue statement, break statement, return statement, and throw statement ) must be terminated with semicolons. Such semicolons may always appear explicitly in the source text.

Your statement that the example given by the OP doesn't require (or is optional) is correct. The reasoning that got you there is flawed. There are instances in JS where semicolons are REQUIRED. Stated as an absolute semicolons are NOT optional in JS, but there are many cases where automatic semicolon insertion will make it seem so.

TonyLa
A: 

As long as you break lines, JS interpreters may not require semicolon. Personally, I prefer to see semicolon for two reasons: compression and readability.

netrox