DEV Community

Discussion on: What you need to know about Javascript's Automatic Semi-colon Insertion

Collapse
 
math2001 profile image
Mathieu PATUREL • Edited

Good post!

Just a little typo in the first example:

const foo = {
  semi: 'not semi'
}
const val1 = foo
['semi']
console.log(val) //not semi

This would actually throw a ReferenceError, since val isn't defined (you define val1 before, not val)

I never use semi colons, except when I have to...

The only time I needed to do so was when I wrapped some code in a self calling function, like so:

(function () {
   console.log('*My* code!')
)()

If the previous line doesn't finish with a semi colon and that one isn't inserted automatically, for example, let's say the previous line was:

(function () { console.log('An other script') })()

What is going to happen is that my code is going to try to call the return value of the function just above (which is undefined), since there isn't any semi colon.

The whole code formatted so that it's easier to understand:

(function () {
    console.log('An other script')
})()(function () {
   console.log('*My* code!')
})()

This gives you:

Uncaught TypeError: (intermediate value)(...) is not a function
    at <anonymous>:3:5

The really vicious thing is that there is this problem when loading scripts in different <script> tag:

This is my buggy html page

<script src="myscript1.js"></script>
<script src="myscript2.js"></script>
// myscript1.js

(function () {
   console.log('This is my first script (it works)')
})()

// myscript2.js

(function () {
    console.log('But this doesn\'t...')
})()

The solution? Put a semi colon before every self calling function:

;(function () {
    console.log("this works in every case!")
})()

Did you know you could put more than one semi colon?

console.log("this");;;
console.log("works!");;;;;

Just a funny useless thing... :smile:

Collapse
 
promisetochi profile image
Promise Tochi

Yeah, thanks for pointing out the typo.

The multiple semi-colon is interpreted as multiple statements. Also the multiple IIFEs thanks for pointing that out too.