Context
Reviewing scripts to prepare minimized files, I have found a couple of functions that have caught my attention due to their structure.
the exclamation
The first, because it uses an exclamation mark !
at the beginning of the function:
!function(a, b, c) {
/* ... */
}(jQuery, window, document);
Semicolon
The second because it uses a semicolon ;
at the beginning of the function and enclosed in parentheses.
;(function(a, b, c) {
'use strict'
/* ... */
}($, window, document));
Ask
I know little about javascript and I had not seen this type of structure before.
What meaning do these symbols have in front of a function and when should they be used?
Semicolon
For the
;
The simple explanation is that in order to concatenate several javascript files that have "n" number of functions and guarantee that an unexpected error does not occur, the is prepended;
to prevent any file prior to this from generating an error as it does not have the correct closure in the function.In a few words, it serves as a security measure to prevent a previous function from not being closed correctly and generating an error. The correct thing to do is always make sure to end the functions with
;
but many times you have to work with third-party libraries and since there is no guarantee because the code is not known in depth, this security measure is implemented.For more information on this subject, you can review the link suggested by @Pikoh : Prefix a semicolon to a javascript function
the exclamation
On the other hand, the exclamation mark is used for several things:
1) Automatically insert a
;
at the end of the function so you avoid errors when concatenating javascript files.2) Save a byte in the expression because it would normally read as:
The parentheses around the function make it a bit unreadable and confusing. To solve this, the exclamation mark is also prefixed, in addition you would be using one character
!
instead of two()
, hence the fact that you save a byte per function in which you use this mark.3) The most obvious part is that it is used for the expression to return the boolean value
true
For more information on this other point, you can visit the link suggested by the user @Pikoh : Prefix an exclamation point to a javascript function
I hope to be helpful. All the best!