Reputation: 113
Importance of using ! in this code
var testValue;
!function test() { testValue = 3; }();
console.log(testValue);
Upvotes: -1
Views: 70
Reputation: 390
Functions are not automatically objects. You should define it inside brackets or assign it to a variable. If you use ! for function definition. It means !(function(){console.log("hi");}) Now you can insert () to run that function.
Upvotes: 0
Reputation: 371168
The !
indicates to the interpreter to parse what follows as an expression rather than as what would otherwise be a function declaration. Function declarations can't be invoked on the same line, so without the !
, a SyntaxError
would be thrown:
var testValue;
function test() { testValue = 3; }();
console.log(testValue);
Only function expressions can be immediately invoked. Though, to indicate a function expression, it would probably be clearer to use parentheses around the function rather than !
, and there isn't all that much point to naming the function test
if the function name isn't used anywhere, eg:
var testValue;
(() => {
testValue = 3;
})();
console.log(testValue);
Upvotes: 3