Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you explain this structure in JavaScript?

(function() 
 {
     //codehere
 }
)();

What is special about this kind of syntax? What does ()(); imply?

like image 486
user21572 Avatar asked Oct 09 '08 05:10

user21572


People also ask

How do you define a structure in JavaScript?

In JavaScript, an object is a collection of key-value pairs. This data structure is also called map, dictionary or hash-table in other programming languages. We use curly braces to declare the object. Then declare each key followed by a colon, and the corresponding value.

What are the four basic data structures in JavaScript?

The four types of basic data structures supported by JavaScript are: array lists, maps, records and JSON tables.

What are JavaScript data types explain in detail?

In Javascript, there are five basic, or primitive, types of data. The five most basic types of data are strings, numbers, booleans, undefined, and null. We refer to these as primitive data types. A single variable can only store a single type of data.


2 Answers

The creates an anonymous function, closure and all, and the final () tells it to execute itself.

It is basically the same as:

function name (){...}
name();

So basically there is nothing special about this code, it just a 'shortcut' to creating a method and invoking it without having to name it.

This also implies that the function is a one off, or an internal function on an object, and is most useful when you need to the features of a closure.

like image 73
Geoff Avatar answered Sep 24 '22 00:09

Geoff


It's an anonymous function being called.

The purpose of that is to create a new scope from which local variables don't bleed out. For example:

var test = 1;
(function() {
  var test = 2;
})();
test == 1 // true

One important note about this syntax is that you should get into the habit of terminating statements with a semi-colon, if you don't already. This is because Javascript allows line feeds between a function name and its parentheses when you call it.

The snippet below will cause an error:

var aVariable = 1
var myVariable = aVariable

(function() {/*...*/})()

Here's what it's actually doing:

var aVariable = 1;
var myVariable = aVariable(function() {/*...*/})
myVariable();

Another way of creating a new block scope is to use the following syntax:

new function() {/*...*/}

The difference is that the former technique does not affect where the keyword "this" points to, whereas the second does.

Javascript 1.8 also has a let statement that accomplishes the same thing, but needless to say, it's not supported by most browsers.

like image 35
Leo Avatar answered Sep 27 '22 00:09

Leo