Javascript Does a self-running anonymous function provide enough protection for variables from the global namespace?

Would this code be better written using closure? Is there a better way to write this, or does a function protect variables?

(function(){

    var http = require('http'),
        port = process.argv[2],
        string = "",
        length = 0; 

    http.get(port, function(res){

        res.on('data', function(data){
            length += data.length;
            string += data;
        });

        res.on('end', function(){
            console.log(length);
            console.log(string)
        });
    });

})();
+4
source share
1 answer

This saves the variables within itself and beyond the reach of any external code:

(function() {
  var so = '//stackoverflow.com';

  alert(so); will alert '//stackoverflow.com'
})();

alert(so); // Will alert Undefined **See note at bottom

Take a look at his post I found with google quick search

Note. . As stated in the comment below, this will not warn Undefined, but actually throws a reference error, since it sowill not be present in the area outside of IIFE. Look at MDN to find out more!

+3

All Articles