Aran Mulholland
Aran Mulholland

Reputation: 23935

Javascript: Situation with no semi colon needed?

I am setting up some data to do an AJAX post and the code looks like this.

var data = {}
data.someId= 3;
data.anotherId = 4;

and this works fine. But why don't I need a semi-colon at the end of the first line?

Upvotes: 1

Views: 403

Answers (6)

Connor Smith
Connor Smith

Reputation: 1314

They are optional. You don't need any of those.

https://mislav.net/2010/05/semicolons/

Upvotes: 5

Steph M
Steph M

Reputation: 2172

Sometimes your Linter settings will trigger if you don't use semicolons in places where your Linter is set up to detect them. However, some semicolons are optional in JavaScript including the semicolons put just before a line-break. Thanks to automatic semi colon insertion (ASI).

ASI is just a set of rules for when semicolons are optional, it doesn't actually insert semicolons into your code.

Some semicolons ARE necessary. Sxamples of necessary semicolons include the head of the a for loop and do-while loops.

Also be careful because although omitting optional semi-colons is valid code some tools like minifiers are written to interpret those semicolons so it could throw an error with one of those tools.

Upvotes: 0

Denis de Bernardy
Denis de Bernardy

Reputation: 78443

Semi-colons are optional in javascript. But it is recommended to add it.

Upvotes: 0

alex
alex

Reputation: 490233

Because JavaScript has Automatic Semicolon Insertion.

I erroneously called it Automatic Semicolon Injection earlier, which kind of makes sense :P

The language requires them, but it preprocesses your script and tries to guess where they should go. This doesn't always work out, as you can see in pst's comment.

You should just define the semi colons yourself. Don't let JavaScript guess.

Upvotes: 5

djibouti33
djibouti33

Reputation: 12132

JavaScript actually doesn't require semicolons to determine the end of a statement. If no semicolon is present, it will use a new line as the end of the statement. The only time it's necessary to use a semicolon is if you want to put two statements on the same line, one right after another.

All this being said, it's best practice to always end your statements with semicolons To avoid confusion and to avoid bugs that could be painful to find.

Upvotes: 0

maaudet
maaudet

Reputation: 2358

A semi colon for a single statement on a line is not required in Javascript.

Upvotes: 0

Related Questions