-1

I observe a different (different for me) way to write function of javascript or jquery,,,you guys kindly guide me about the working of this one.

(function () 
{
//some statements of javascript are sitting here
//some statements of javascript are sitting here
//some statements of javascript are sitting here
//some statements of javascript are sitting here
//some statements of javascript are sitting here
}()); 

Truly I'm not understanding (function(){}());.

No one is calling it but it is being called properly.

If any piece of tutorial you guys know, concerned to it, then tell me.

Richard Ev
  • 52,939
  • 59
  • 191
  • 278
Adeel Akram
  • 390
  • 2
  • 4
  • 12
  • Does this answer your question? [What is the (function() { } )() construct in JavaScript?](https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) – rainbow.gekota Nov 03 '22 at 04:59

2 Answers2

5

That is a Immediately-Invoked Function Expression (IIFE). In other words, a function that gets executed when defined

davids
  • 6,259
  • 3
  • 29
  • 50
  • I thought they were called anonymous and self-executing or something. – Anirudh Ramanathan Nov 15 '12 at 10:47
  • A.K.A. Self-Executing Anonymous Function – Christofer Eliasson Nov 15 '12 at 10:47
  • 1
    @Cthulhu - They have all sorts of names. Ben Alman coined IIFE, which probably most accurately describes the construct - the other names don't make it clear you have a function expression rather than a declaration. – James Allardice Nov 15 '12 at 10:48
  • Wow but javascript encourages some absolutely horrible practices. I'd never come across this one before, but that is just hideous coding. – PaulMolloy Nov 15 '12 at 10:49
  • 1
    @PaulMolloy: I don't see what's horrible about it but it's very common and it makes total sense when JS only has function scope and the parenthesis are optional, just a convention, you can write: `function(){}()` – elclanrs Nov 15 '12 at 10:51
  • @PaulMolloy - It's not hideous at all. It's a very common way to introduce a new scope within a block (and it creates a closure to capture the value of variables in the parent scope too, which is very useful when declaring functions in loops e.g. event handlers). – James Allardice Nov 15 '12 at 10:51
  • @eclanrs do you mean (function(){}()); is replaced by function(){}() – Adeel Akram Nov 15 '12 at 11:00
0

Declaring a function without a name is normally used to assign that function into a variable. A useful trick which allows you to pass the entire function around and call it later. In this case it's not being assigned to anything, but the extra set of brackets after the braces are effectively calling the function immediately.

PaulMolloy
  • 612
  • 6
  • 13