Dấu ! trước function chỉ ra đây là IIFE (Immediately Invoked Function Expression) - function thực thi ngay lập tức.
Cú pháp
!function foo() {}()
Dấu () cuối cùng mới thực sự gọi function. () có precedence cao hơn !.
Các biến thể
(function(){})(); // Phổ biến nhất - parentheses grouping
(function(){}()); // Cũng OK
+function(){}(); // Unary plus
-function(){}(); // Unary minus
~function(){}(); // Bitwise NOT
void function(){}(); // void operator
Tại sao dùng ! / + / - / ~ / void?
- Ép parser parse function keyword như expression không phải declaration.
- Function declaration bắt buộc có tên:
function foo() {}. - Function expression có thể anonymous:
function() {}. - Nếu viết
function(){}()→ SyntaxError (parser thấy declaration thiếu tên).
Giá trị trả về
- IIFE mặc định trả
undefined. !undefined=true.+undefined=NaN.-undefined=NaN.~undefined=-1.void undefined=undefined.
Thường kết quả bị bỏ qua (không gán biến). Mục đích là tạo scope.
Modern Alternative
- Block scope với
let/const(ES6). - ES Modules (
type="module") - tự động module scope. - IIFE vẫn dùng: legacy, bookmarklet, userscript, bundle wrapper.