Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between using a semicolon, an exclamation point, or a plus sign, at the beginning of JavaScript files?

Tags:

javascript

In JavaScript files, I have seen these 3 forms:

;(function() {
    // content ...
}());

and

!function() {
    // content ...
}();

Or in Bootstrap's js file:

+function() {
    // content ...
}();

I think the ;, !, or + is there so that if many files are concatenated together, the ;, !, or + can separate it from previous file's content.

What is the difference between using ;, !, or +? Is one method better than the others?

like image 221
nonopolarity Avatar asked Oct 29 '22 10:10

nonopolarity


1 Answers

;(function() {
    // content ...
}());

The semi-colon terminates an empty statement which is followed by a conventional IIFE. This has no effect, but might be useful as a notation.

!function() {
    // content ...
}();

The exclamation causes the statement that follows to be treated as an Expression. See Also: What does the exclamation mark do before the function. This is a 1 byte shorter method of expressing an IIFE.

+function() {
    // content ...
}();

Very similar to the exclamation point version, both of them cause the following statement to be evaluated as an expression. The difference is how the result of the expression is treated. The + causes it be converted to a numeric value, the ! causes the value to be negated. In both cases the result is then discarded - they are effectively the same.

like image 114
Tibrogargan Avatar answered Nov 15 '22 03:11

Tibrogargan