Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js JavaScript syntax [duplicate]

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.

like image 704
Terry Chen Avatar asked Mar 07 '14 18:03

Terry Chen


People also ask

How do you repeat a node js code?

You use repeating to print repeating strings: const repeating = require('repeating'); console. log(repeating(100, 'unicorn '));

How do you clone in node JS?

The cloneNode() method creates a copy of a node, and returns the clone. The cloneNode() method clones all attributes and their values. Set the deep parameter to true if you also want to clone descendants (children).

What is the use of buffer copy ()?

The Buffer. copy() method simply copies all the values from input buffer to another buffer.


1 Answers

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?

like image 164
webpapaya Avatar answered Sep 18 '22 13:09

webpapaya