Skip to content

JavaScript private variable | Basics

  • by

The private variable is only visible to the current class and not accessible in the global scope or to any of its subclasses. ES6 standard does not offer a new way of defining private variables in JavaScript.

Alternatively, we may also use the “this” keyword to make method (function) calls to stick to the main method itself which thus makes the variables private.

JavaScript private variable

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>

   function Foo(b)
   {
     var bar = b;

     this.setBar = function(x){
      bar = x;
    }

    this.alertBar = function(){
      console.log(bar);
    }
  }

  var test = new Foo(10);
  test.alertBar()

  console.log(test.bar); //undefined because private
</script>

</body>
</html> 

Output:

JavaScript private variable

Another modern approach to achieving privacy in JavaScript is through the use of ES6 classes and symbols. Symbols are unique and can be used as property keys to make it harder for external code to access certain properties, but it doesn’t make them completely private.

const _count = Symbol('count');

class Counter {
  constructor() {
    this[_count] = 0;
  }

  increment() {
    this[_count]++;
  }

  getCount() {
    return this[_count];
  }
}

const counter = new Counter();

console.log(counter.getCount()); // 0
counter.increment();
console.log(counter.getCount()); // 1

How to set javascript private variables in the constructor?

Answer: You have to put all functions that need to access the private variable inside the constructor:

function Foo(bar)
{
  //bar is inside a closure now, only these functions can access it
  this.setBar = function() {bar = 5;}
  this.getBar = function() {return bar;}
  //Other functions
}

var myFoo = new Foo(5);
myFoo.bar;      //Undefined, cannot access variable closure
myFoo.getBar(); //Works, returns 5

Do comment if you have any doubts or suggestions on this JS variable topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *