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>

   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

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() {

  getCount() {
    return this[_count];

const counter = new Counter();

console.log(counter.getCount()); // 0
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);;      //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 *