The problem is eluded to in the code compiled by Babel: the two lines you have given it are interpreted as one.
Is it still a dangerous practice to not use semicolons?
In my opinion, no. White-space is collapsed in JavaScript meaning multiple lines can be interpreted as one, so there are a few cases in which they are necessary, but whether this means that using semi-colons is an absolute must is really down to personal preference. Some people feel very strongly that you should, and they may well be right...
Anyhow, as you discovered, one of these cases is ending a line with an object or array and starting the next with an array literal ([]
). You can read about the remaining cases here.
If the code you are working on does not use semi-colons, for example if it uses the standard code style, you can..
..add a semi-colon to the end of the first line:
var obj = {a:1};
[1,2,3].forEach(console.log)
..add a semi-colon to the beginning of the second line:
var obj = {a:1}
;[1,2,3].forEach(console.log) // beginning of last line
..avoid having to use a semi-colon at all by assigning the array literal to a variable:
var obj = {a:1}
var arr = [1,2,3]
arr.forEach(console.log)
____
Side note...
The reason the contents of your array literal are wrapped in brackets is because Babel has interpreted your array literal as an attempt to access a property on the object literal defined in the previous line. Of course, you can only access one property at a time using the array[index]
syntax, so Babel uses the comma operator to take a single value from (1, 2, 3)
, which will be 3
.
Read about the comma operator on MDN.