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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read