Reputation: 225
In a code in TypeScript I saw
(() => {
const abc = 'blabla';
...
})();
What does this syntax mean exactly ? I know arrow functions is JS - so I understand this:
() => {
const abc = 'blabla';
...
});
But what is the interest of the rest of parenthesis ?
PS: The original code is
(() => {
const title = 'New Document'
NewDoc.initialize = () => {
render(
<App title={title} />,
document.querySelector('#contnr')
);
};
render(
<Progr />,
document.querySelector('#contnr')
);
})();
Thank you
Upvotes: 0
Views: 1236
Reputation: 7294
In JavaScript these functions are called IIFE (Immediately-Invoked Function Expression), it's just a definition of a function and invoking it immediately! What is it good for? many reasons...
But, before we go into the reasons, please note that arrow functions are not part of your question, as there's not this
in your example...
Also not that this question is not relevant to TypeScript.
Few on many reasons:
Upvotes: 2
Reputation: 4101
The trailing ()
call the anonymous function. This is also possible with function
s.
Since your code already makes use of ES6 features, a simple block of curly braces can be sufficient. In your example, it restricts the scope of title
to the curly braces which makes the code more predictable. The title
constant is not visible before {
and after }
(it does not pollute the rest of your file):
{
const title = 'New Document'
NewDoc.initialize = () => {
render(
<App title={title} />,
document.querySelector('#contnr')
);
};
render(
<Progr />,
document.querySelector('#contnr')
);
}
In the same file, you may now have a second block of curly braces and do something else with a different title, without having to modify the first title:
{
const title = 'Other Document'
// do something with "title"
}
Hint: Avoid var
declarations. They are not useful any more with ES6 because const
and let
are available, and the scopes of var
variables do not respect simple curly braces.
Upvotes: -1
Reputation: 441
Your code can be decomposed from
(() => {
const title = 'New Document'
NewDoc.initialize = () => {
render(
<App title={title} />,
document.querySelector('#contnr')
);
};
render(
<Progr />,
document.querySelector('#contnr')
);
})();
to...
const myFunc = () => {
const title = 'New Document'
NewDoc.initialize = () => {
render(
<App title={title} />,
document.querySelector('#contnr')
);
};
render(
<Progr />,
document.querySelector('#contnr')
);
}
(myFunc)();
The parenthesis you are seeing is wrapping the lambda (anonymous function) in parenthesis so you can call it.
Upvotes: 0