Wednesday 10 April 2019

Why enclose javascript file in a function?




I've been playing around with Node.js after having not used JavaScript for a long time.



One thing I've noticed is that many of the sample files I've been looking at use the following convention:



(function() {
... all javascript code for the file ...
})();



Is there a reason to enclose all the JavaScript in a file in a function like that, or is it just convention? Is it something I should mimic?



I should also note, that at least in the files I've been playing with, the code works the same way with or without the function surrounding everything.



Thanks for your insights!


Answer



Variables in Javascript have function scope. You're wrapping your code in a function in order for it not to clobber the global namespace with tons of variables, which may lead to bugs later on when different code is added. E.g.:



// module 1
(function () {

var foo = 'bar';
...
})();

// module 2
(function () {
var foo = 'baz';
...
})();



No problems, because both modules have their own variable scopes.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...