I saw this syntax many times but I couldn’t find a way to google it properly, I hope I can get some help here:
<script>
(function(){
//code goes here
})();
</script>
Why is the function keyword wrapped in the parenthesis? What does it do and what is this called?
In js, the syntax:
defines an anonymous function. You can store this into a variable and call it:
or if you don’t want to bother assigning it you can do it in one step.
the parenthesis are necessary because:
is not proper syntax.
This syntax is useful in certain situations to help memory management as well as change variable names. For example in javascript you have a
jQueryobject, but most people refer to it as$. But sometimes$is used as some other variable instead of the jQuery object. To fix this, you can wrap your code in:That way you can use the dollar sign and not have to worry whether or not it actually points to the jQuery object or not.