Category: ES6+ (ECMAScript 6+)

JavaScript ES6+ : Syntaxes for implementing private methods, private properties, static properties and static methods in JavaScript class

In this article i am going to explain how to use private methods, properties and static methods and properties in ES6+ based JavaScript class. If you have previous programming experience with OOP (Object Oriented Programming) Language, you may have used private, public and static methods and properties. Today we will look at how the same functionality is achieved with JavaScript.

Lets start our article here.

 

Private methods.

private methods are used only within the class and they are intended to be used by the methods within the class. since the access level is private, those methods cannot be invoked from outside of the application.

 

Why do we need private methods?

First of all we should look at the reason behind the need of the private methods. Those reasons can be described as follows.

  • prevent the code duplication

In your software development life, you might have seen that there are some common logic in a class that need to be reused in more than one method of the same class. So if we do not separate those logic/codings into a separate method, we have to duplicate them in every method. In such case we might need a private method.

  • Improve the code readability and cleanliness. 

Sometimes you might have noticed that there some methods which are lengthy due to many number of code lines. Therefore it is very difficult to read the method contents. Therefore the readability of the method goes down. If you observe those methods carefully,  you can find some similar set of logics that can be separated into groups. So separating those similar logics (groups) into a private methods, may improve the readability of your source code.

Therefore it is good idea to separate and group the similar logic into a private methods which will improve the cleanliness, reusability and readability of your source code.

Ok. enough theories.  Lets look at some coding examples here.

for the demonstration purpose, i will use simple example from java programming language and convert it into the the JavaScript ES6. Then you will be able to understand them easily by comparing each of them.

 

Private members 

First we will look at how to add a private property (member variable) for a class. In java, this can be simply achieved as follows.

 

public class Sample
{
 private String privateProperty;

 public String getPrivateProperty(){
   return privateProperty;
 }
}

 

The same thing can be achieved with JavaScript ES6 is as follows.

let  privateProperty;

class Sample
{
    getPrivateProperty()
    {
        return privateProperty;
    }
}

 

If you want to declare a private property in ES6, it should be declared outside of the class.  Then even if the class is instantiated, the private property cannot be accessed because, it does not belong to the scope of the class.

 

Static properties and methods

In java we can add static members and static methods as follows.

public class Sample
{
    static String staticProperty;
 
    //getter for the static property
    public String getPrivateProperty()
    {
        return staticProperty;
    }

    //another static method 
    public static String sayHello(){
        return "hello";
    }
}

 

The same thing can be achieved with javascript as follows.

let staticProperty;

class Sample
{
    //getter for the staticProperty
    static getStaticProperty()
    {
        return staticProperty;
    }

    //we can add static modifier for methods to make them as static methods
    static sayHello()
    {
      return "hello";
    }
}

 

In java we can  add the static modifier to member variable for making it as a static field. But in javascript, we cannot add such modifiers.  The only way to achieve static filed is to add a static getter for the field the need to be set as static.

static modifier can be added for the methods to make them as static.

 

Private methods

In java private methods can be declared with private access modifier. please refer the below code segment.

public class Sample
{
    public String displayWelcomeMessage(){
        return this.sayHello();
    }

    private String sayHello(){
        return "hello";
    }
}

 

But in javascript, you have to declare it as follows.

let methods = {
    //the multiple private methods can be added here (by comma seperated)
    sayHello(){
        return "hello";
    }
};

class Sample {
    displayWelcomeMessage() {
        return methods.sayHello();
    }
}

 

 

After reading this article, i believe that you got a good understanding of how to declare private and static fields(members) in javascript ES6. In addition, you should have a good understanding of how to declare static methods in a class. In you need any clarification regarding this article, feel free to contact me.

 

 

ES6+ : var, let and const for variable declarations in JavaScript

var, let and const are keywords used to declare variables in javascript.  var and let describes about the access level (or scope) of the declared variable and const keyword determine whether the value of a variable can be re-assigned.  as the name implies, const keyword is used to declare constant in javascript program. we will look at them in detailed in the following sections.

 

Global and Local  variable declaration with var

var keyword is used to declare the variable in javascript. The most of the resources says that var is used to declare a global variable (globally accessible variable) in javascript. I cannot completely agree with this statement as the access level/scope is determined by the place where the variable is declared.

How to determine the variable scope or access level?

  • If the variable is declared outside a function, it can be used by any function within the same scope. Therefore the variable scope is global (for any function).
  • In the variable is declared inside a function, then it can be accessible only within that method. Therefore the variable scope is known as local (only for that function).

 

Global Scope

Please refer the below example where the “age” has been declared to be a global scope variable.

var age = 20;

function printAge() {
    console.log("age is " + age);
}

function printAgeCategory() {
    if (age >= 18) {
        console.log("adult");
    }
    else {
        console.log("child");
    }
}

printAge(); // will print "age is 20"
printAgeCategory(); // will print "adult"

 

Local Scope

Please refer the below example where the “age” has been declared to be a global scope variable (only for printAge function).

function printAge() {
    var age = 20;
    console.log("age is " + age);
}

function printAgeCategory() {
    if (age >= 18) {
        console.log("adult");
    }
    else {
        console.log("child");
    }
}

printAge(); // will print "age is 20"
printAgeCategory(); // Uncaught ReferenceError: age is not defined

 

printAgeCategory cannot access the age variable as it is declared within the printAge function. it has the local scope within the printAge function and can be accessed only within that function.

 

What is the reason behind introducing let in ES6?

After going through the above example, i am pretty sure that you have the following feeling and you might be questioning yourself about the reason behind “let” keyword for declaring variables.

You might be thinking of “var keyword can be used to declare variables which can have either global or local access. So, why do we need an additional variable declaration keyword like “let“?  What is the real usage of it ?”

 

Let me explain. 

 

Consider the below example.

for (var index = 0; index < 3; index++) {
    console.log("inside for loop [" + index + "]");
}

console.log("outside for loop [" + index + "]");

 

The result/output of above example can be given as follows.

inside for loop [0]
inside for loop [1]
inside for loop [2]
outside for loop [3]

 

Did you notice a wired behaviour by examining about output?  Can you notice that variable index is accessed from outside of the for loop ?  Isn’t it wired?  It is intended to be developed as local variable inside the for loop block. but unfortunately it is not. The solution is to move forward with block scope variables.

ES6 (ECMAScript 2015) has identified above issue and has introduced block scope variable declaration with “let” keyword.

 

“let” keyword for variable declaration in ES6

 

let keyword helps to declare block-scope variables. These variables are scoped in the braces {} (block) .

So the above program can be re-written with let keyword as follows.

for (let index = 0; index < 3; index++) {
    console.log("inside for loop [" + index + "]");
}

console.log("outside for loop [" + index + "]");

 

The result will be as follows.

inside for loop [0]
inside for loop [1]
inside for loop [2]
Uncaught ReferenceError: index is not defined

 

Since the index variable is declared with let, it has the blocked scope within the for loop. Therefore it cannot be accessed outside of the for loop. Trying to access it outside from the block may throw ReferenceError.

 

const

As the name implies the const keyword is used to define constants. The value for the constant should be assigned when it is declared and it cannot be changed/reassigned later.

Const actually means that once the variable is assigned it cannot be assigned again and an attempt to do so will throw an error.

const defends the variable from being overwritten.

const i = 0;
i = 1; // TypeError: Assignment to constant variable.

 

const, like let, is block scoped.

consider the below code segment which tries to reassign a value for the const variable.

if (true) {
  const i = 0;
}
console.log(i); // ReferenceError: i is not defined

 

const does allow mutability: the value can change if it’s mutable, such as an Object or an Array.

const obj = {
  i: 0
};
obj.i = 1; //here it is legal because we are not going to assign new object to 'obj'
obj.i; // 1  (legal and prints '1')