Search code examples
javascriptprivate-members

Why do we need private variables?


What are they for and how do we make it? Can you give me an example?


Solution

  • To avoid collisions with multiple libraries, for example.

    Say they both use a variable commonly used such as data. If both libraries use private variables it's all fine:

    var lib1 = (function() {
        var data;
    
        return {
            get: function()  { return data },
            set: function(v) { data = v }
        };
    })();
    
    // Supposed to do something different:
    var lib2 = (function() {
        var data;
    
        return {
            get: function()  { return data },
            set: function(v) { data = v }
        };
    })();
    
    lib1.set(123);
    lib2.set(456);
    lib1.get(); // 123
    lib2.get(); // 456
    

    However suppose they don't use private variables but global ones like this:

    var lib1 = (function() {
        return {
            get: function()  { return data },
            set: function(v) { data = v }
        };
    })();
    
    // Supposed to do something different:
    var lib2 = (function() {
        return {
            get: function()  { return data },
            set: function(v) { data = v }
        };
    })();
    
    lib1.set(123);
    lib2.set(456);
    lib1.get(); // 456 - overwritten by lib2. lib1 might not work properly anymore.
    lib2.get(); // 456
    

    So lib1.get() will fetch the same data as lib2.get().

    This example is too obvious of course but to stay safe it's a good practice to use private variables.