0

I have never writen vanilla js before and today I saw some code. There was a JavaScript file that started with:

(function ($) {...})

and they had written all the code inside this function. What is the purpose of this usage? And what is the name of this usage?

Cyrus Raoufi
  • 526
  • 1
  • 3
  • 27
b_ozcan
  • 19
  • 3
  • 2
    It's called an [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) – nullptr Aug 26 '22 at 11:22
  • 4
    @nullptr That's not an IIFE since it's not Immediately Invoked. – AKX Aug 26 '22 at 11:25
  • 2
    That construct on its own doesn't do anything (useful). There should be a `(jQuery)` (most likey, or any other library that uses `$`) right behind that `})` -> `(function ($) {...})(jQuery)` – Andreas Aug 26 '22 at 11:29
  • @Andreas yes there was. – b_ozcan Aug 26 '22 at 12:00
  • @AKX it's not an iife only because op was missing the invoking part lol – nullptr Aug 30 '22 at 09:23
  • @nullptr yes, which makes it nothing more than a [function expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function). – AKX Aug 30 '22 at 09:24

0 Answers0