(function createTaskRecord() {
// with some details
}()) // <--- whats the use of parentheses after the } ?
I am new to Javascript and wish to understand what are functions with ()
in the end called ? Why are they used and when ?
(function createTaskRecord() {
// with some details
}()) // <--- whats the use of parentheses after the } ?
I am new to Javascript and wish to understand what are functions with ()
in the end called ? Why are they used and when ?
This is called immediate execution. This will evaluate your function immediately.
Actually there is a more formal name for functions that are defined with this way: IIFE (Immediately Invoked Function Expression).
Wikipedia has a great article about them:
An immediately-invoked function expression (or IIFE, pronounced "iffy") is a JavaScript design pattern which produces a lexical scope using JavaScript's function scoping. Immediately-invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function. This pattern has been referred to as a self-executing anonymous function, but Ben Alman introduced the term IIFE as a more semantically accurate term for the pattern, shortly after its discussion arose on comp.lang.javascript.