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>

   function Foo(b)
     var bar = b;

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

    this.alertBar = function(){

  var test = new Foo(10);

  console.log(; //undefined because private



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);;      //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 *