How to create a private variable in JavaScript ?
Last Updated :
14 Jan, 2022
In this article, we will try to understand how we could create private variables in JavaScript. Let us first understand what are the ways through which we may declare the variables generally in JavaScript.
Syntax: By using the following syntaxes we could declare our variables in JavaScript.
var variable_name = value
Also, another syntax that we could use for variable declaration is by using the "let" keyword.
let variable_name = value
Now that we have a basic idea about how we could declare the variables, let us see how to make them private which is making these variables inaccessible directly.
Private Variables creation in functions: Whenever we deal with functions we always try to make variables private which then helps not to directly access variables further avoids updating these values too.
Example: The implementation of the code will eventually assist us in understanding how to build private variables and functions:
JavaScript
<script>
function carDetails() {
let kms = 0;
let speed = 0;
let speedUp = (intialSpeed) => {
speed += intialSpeed;
kms += speed;
};
let totalkmsDriven = () => kms;
return { speedUp, totalkmsDriven };
}
let car_object = carDetails();
car_object.speedUp(7);
car_object.speedUp(9);
console.log(car_object.totalkmsDriven());
// Undefined, since it is made private:
console.log(car_object.kms);
</script>
Output:
23
undefined
All the variables declared (shown in the above code snippet) can't be accessed directly since they are encapsulated in such a way that without the function call access the values carried by these variables can't be used or printed out.
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. The main idea for using the "this" keyword is just to make things directly visible that is making methods directly accessible. Following is the code snippet shown for better understanding:
JavaScript
<script>
function carDetails() {
let kms = 0;
let speed = 0;
this.speedUp = (intialSpeed) => {
speed += intialSpeed;
kms += speed;
};
this.totalkmsDriven = () => kms;
}
let car_object = new carDetails();
car_object.speedUp(7);
car_object.speedUp(9);
console.log(car_object.totalkmsDriven());
// Undefined, since it is made private:
console.log(car_object.kms);
</script>
Output:
23
undefined
Private Variables creation in classes: In ES6 we have a facility in the form of classes that are also used in terms of displaying certain output over the user's console. While declaring a class we also use the constructor function which is nothing but the default function which accepts certain parameters while calling certain variables or methods after making the object.
In order to demonstrate variable privacy, we will put all the things inside the constructor function, and then further we will access them via certain methods (it could also be referred to as encapsulation in which we access variables via methods).
Following is the code snippet which demonstrates the above-illustrated facts:
JavaScript
<script>
class carDetails {
constructor() {
let kms = 0;
let speed = 0;
this.speedUp = (initialSpeed) => {
speed += initialSpeed;
kms += speed;
};
this.totalkmsDriven = () => kms;
}
}
let car_object = new carDetails();
car_object.speedUp(12);
car_object.speedUp(13);
console.log(car_object.totalkmsDriven());.
// Undefined...since it is made private:
console.log(car_object.speed);
</script>
Output:
37
undefined
Similar Reads
How to create Static Variables in JavaScript ? To create a static variable in JavaScript, you can use a closure or a function scope to encapsulate the variable within a function. This way, the variable maintains its state across multiple invocations of the function. Static keyword in JavaScript: The static keyword is used to define a static meth
2 min read
How to Create a String with Variables in JavaScript? To create a string with variables in JavaScript, you can use several methods, including string concatenation, template literals, and the String methods. Here are the common approaches:1. Template Literals (Recommended)Template literals are the modern and most preferred way to create strings with var
2 min read
How to Declare Multiple Variables in JavaScript? JavaScript variables are used as container to store values, and they can be of any data type. You can declare variables using the var, let, or const keywords. JavaScript provides different ways to declare multiple variables either individually or in a single line for efficiency and readability.Decla
2 min read
How to create a variable using a user-defined name in JavaScript ? In this article, we will learn to create a variable using the user-defined name in JavaScript. Variables in JavaScript: Basically, it is a container that holds reusable data in JavaScript. The variable's value can be changed during program execution and should be declared before using it. Before ES6
2 min read
How to declare Global Variables in JavaScript ? Global Variables Global variables in JavaScript are variables declared outside of any function. These variables are accessible from anywhere within the script, including inside functions. Global variables are declared at the start of the block(top of the program)Var keyword is used to declare variab
2 min read
How to Use Dynamic Variable Names in JavaScript? Dynamic variable names are variable names that are not predefined but are generated dynamically during the execution of a program. This means the name of a variable can be determined at runtime, rather than being explicitly written in the code.Here are different ways to use dynamic variables in Java
2 min read
How to use JavaScript Variables in Ruby? JavaScript and Ruby are two powerful programming languages used extensively in web development. While each language has its own set of features and capabilities, there are times when developers may need to integrate functionalities from one language into the other. One common scenario is using JavaS
4 min read
How to create an object with prototype in JavaScript ? In this article, we will discuss object creation & prototypes, along with understanding the different ways for object creation & their implementation through the examples. Prototypes are the mechanism by which objects in JavaScript inherit features from another object. A prototype property i
4 min read
How to make variables private in Constructor functions in JavaScript ? In Javascript there's no specific way to make variables private in a Constructor function. If a variable is genuinely private, meaning it cannot be accessible from the outside. A constructor is a function that generates a new instance of a class, sometimes referred to as an "object." A constructor's
2 min read
How to use a closure to create a private counter in JavaScript ? A closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer functionâs scope from an inner function. Example: Here the inner forms closure with outer. The str variable
4 min read