1

I have seen the bitwise operator used in a self calling function, see below example, so I have a simple question, what does it do?

~(function() {

        alert("Hello World");

    })();
Akhil Aravind
  • 4,977
  • 13
  • 31
Ben Osborne
  • 141
  • 2
  • 13
  • 1
    it does nothing special in this case - that's actually redundant ... – Jaromanda X Jun 18 '18 at 09:07
  • https://stackoverflow.com/questions/13341698/javascript-plus-sign-in-front-of-function-name – Satpal Jun 18 '18 at 09:08
  • I'm doubtful that's the real code. For the `~` to have any meaning, the function in question would have to return something. – CertainPerformance Jun 18 '18 at 09:08
  • 1
    `~function() { alert("Hello World"); }();` is an alternative to `(function() { alert("Hello World"); })();` - but what you wrote is redundant – Jaromanda X Jun 18 '18 at 09:09
  • 1
    Well, ~undefined becomes -1 so it does *something*. – ippi Jun 18 '18 at 09:09
  • but the result is discarded, so it does nothing special or relevant or useful - and it is redundant – Jaromanda X Jun 18 '18 at 09:10
  • @CertainPerformance: Not quite. Every JS function returns _something_, even if it's just the default `undefined`. And `~(undefined)` is `-1`. It has meaning. It just doesn't have *purpose*. – Amadan Jun 18 '18 at 09:10
  • by the way, you could also use `!`, `+` or `-` with the same effect - it's a way to create an IIFE – Jaromanda X Jun 18 '18 at 09:10
  • 1
    it forces the expression to evaluate, as `void` would do (with this only use case). – Nina Scholz Jun 18 '18 at 09:12
  • the most common IIFE pattern is `;(function() { ...code...})();` - yes, leading `;` "to be sure" – Jaromanda X Jun 18 '18 at 09:13
  • @NinaScholz - I did not know about `void` – Jaromanda X Jun 18 '18 at 09:14
  • @Amadan - Well, if we're going to be pedantic, a JavaScript function doesn't always return something -- but *calling* the function always produces a value (provided it doesn't throw); if the function didn't return anything, the value produced by calling it is `undefined`. The spec actually differentiates falling off the end of the function vs. using `return` and, for the former, fills in the `undefined` later. (Details in and around [here](https://tc39.github.io/ecma262/#sec-ecmascript-function-objects-call-thisargument-argumentslist).) But it's fairly extreme pedantry at that point. :-) – T.J. Crowder Jun 18 '18 at 09:22

0 Answers0