Friday, July 5, 2019

Node.js JavaScript syntax




I see a piece of JavaScript code in my Node.js application.



( function() { console.log("gg") } )(this)


I would like to know why use => ( function(){} )(this) this type of structure, and how does this compile.



I am understanding why we have this two brackets ()(), and why this code would work.



Answer



This is a self invoking anonymous function. This pattern is useful when you want to hide variables from the global namespace.



(function(){
var foo = "foo";
})();

console.log(window.foo); // undefined



Also see What do parentheses surrounding a JavaScript object/function/class declaration mean?



What advantages does using (function(window, document, undefined) { … })(window, document) confer?


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...