-1

Importance of using ! in this code

var testValue;
!function test() { testValue = 3; }();
console.log(testValue);

2 Answers2

3

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);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Changing the second example from a regular function to an arrow one will create confusion, specially when you state that there will be parenthesis involved, _which ones?_ – ibrahim mahrir Sep 09 '18 at 01:35
0

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.

cemsina güzel
  • 390
  • 4
  • 14