8000 remove duplicate content by lfender6445 · Pull Request #104 · airbnb/javascript · GitHub
[go: up one dir, main page]

Skip to content

Conversation

@lfender6445
Copy link

No description provided.

@hshoff
Copy link
Member
hshoff commented Nov 13, 2013

Hi @lfender6445 thanks for checking out the guide!

I can see how that might look like a duplicate, but there's actually a subtle difference between the two. The second one is prefixed with a ;. This prevents a problem that can occur when concatenating js files.

Let's assume all of the js files follow the IIFE pattern like so:

(function() { console.log('code'); })();

When concatenating a few files together you get something like this:

(function() { console.log('file1'); })();
(function() { console.log('file2'); })();
(function() { console.log('file3'); })();

> file1
> file2
> file3

This is works great. But now let's say file2.js doesn't follow the same style you do and avoids semicolons. You get something like this:

(function() { console.log('file1'); })();
(function() { console.log('file2') })()
(function() { console.log('file3'); })();

> file1
> file2
> TypeError: undefined is not a function

Oh no! With a missing semicolon it tries to invoke whatever was returned from file2.js which in this case is undefined.

A way to safeguard yourself from this is to prefix your IIFE with a semicolon

;(function() { console.log('file1'); })();
(function() { console.log('file2') })()
;(function() { console.log('file3'); })();

> file1
> file2
> file3

Another way to do this and is our preferred modules style (see Modules):

!function() { console.log('file1'); }();
(function() { console.log('file2') })()
!function() { console.log('file3'); }();

> file1
> file2
> file3

For a full explanation on why this happens see here: #44 (comment) & #21 (comment)

🍻

@hshoff hshoff closed this Nov 14, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

0