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 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

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 *