Public, Private, and Protected Scope in JavaScript
Last Updated :
20 Nov, 2023
In this article, we will see the fundamentals of public, private, and protected scopes in JavaScript. We'll explore how to create these scopes, their practical applications, and the conventions used to simulate access control.
ScopesPrivate Scope:
- Private scope in JavaScript is the private members of a class or object that can only be accessed from within the class or object itself.
- To create a private variable or function, you can create using the # prefix. or using closures.
- Private scope can be useful for encapsulating data and behavior within a class or object. This can help to make your code more modular and reusable. It can also help to prevent errors by preventing consumers of your code from accidentally accessing or modifying private members.
When to use Private Scope?
Use private scope for variables and functions that should only be accessible from within the class or object in which they are defined. For example, you might use private scope for the internal state of a class or object, or for implementation details of a method or function.
Example:
JavaScript
let Employee = (function () {
// Private variable
let empName = '';
return class {
constructor(name) {
empName = name;
}
// Private method
getPrivateName() {
return empName;
}
}
})();
const employee = new Employee('Aryan');
// Can access private method
console.log(employee.getPrivateName());
// Cannot access private variable
console.log(employee.privateName);
Output:
privatePublic Scope:
- The Variables and methods declared directly on a class or outside any block are considered public in JavaScript.
- By default, everything declared in JavaScript is public. There is no concept of private/protected by default.
- Public scope can be useful for variables and functions that need to be used by multiple parts of your code. For example, you might use public scope for global variables or functions that are used by all pages of your website.
When to use Public Scope?
Use public scope for variables and functions that need to be accessible from anywhere in your code. For example, you might use public scope for global variables or functions that are used by multiple parts of your code.
Example:
JavaScript
// Public variable
let empName = 'Aryan';
class Employee {
constructor() {
// Public method
this.getName = function () {
return empName;
}
}
}
const employee = new Employee();
// Can access public method
console.log(employee.getName());
Output:
publicProtected Scope:
- Protected members are accessible only within the class itself and its subclasses. Protected methods can access properties by getting them from the WeakMap.
- Protected scope can be useful for variables and functions that need to be accessible from within the class in which they are defined, and from any classes that inherit from that class. For example, you might use protected scope for variables and functions that are shared by all subclasses of a particular class.
When to use Protected Scope?
Use protected scope for variables and functions that need to be accessible from within the class in which they are defined, and from any classes that inherit from that class. For example, you might use protected scope for variables and functions that are shared by all subclasses of a particular class.
Example:
JavaScript
// WeakMap to store protected properties
const protectedMap = new WeakMap();
class Person {
constructor(name) {
// Add property to WeakMap
protectedMap.set(this, {
name
});
}
// Protected method
getName() {
// Access property via WeakMap
return protectedMap.get(this).name;
}
}
// Extend Person class
class Employee extends Person {
constructor(name, title) {
super(name);
// Add additional property
protectedMap.get(this).title = title;
}
getTitle() {
return protectedMap.get(this).title;
}
}
const emp = new Employee('Aryan', 'Manager');
console.log(emp.getName());
console.log(emp.getTitle());
// Doesn't work - protected
console.log(emp.name);
Output:
protected
Similar Reads
Primitive and Reference value in JavaScript In JavaScript, a variable may store two types of values, Primitive values or Reference values. This article will describe and help to compare both these types of values. Primitive value: JavaScript provides six types of primitive values that include Number, String, Boolean, Undefined, Symbol, and Bi
2 min read
Access Modifiers in Python : Public, Private and Protected Prerequisites: Underscore (_) in Python, Private Variables in PythonEncapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be chan
9 min read
Public vs Protected Access Modifier in Java Whenever we are writing our classes, we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not, etc. we can specify this information by usi
4 min read
Public vs Protected vs Package vs Private Access Modifier in Java Whenever we are writing our classes we have to provide some information about our classes to the JVM like whether this class can be accessible from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not etc. we can specify this information by usi
7 min read
Protected vs Private Access Modifiers in Java Access modifiers are those elements in code that determine the scope for that variable. As we know there are three access modifiers available namely public, protected, and private. Let us see the differences between Protected and Private access modifiers. Access Modifier 1: Protected The methods or
2 min read
Modular Scope in JavaScript Modular scope in JavaScript refers to the practice of creating isolated scopes within modules, ensuring that variables and functions are not exposed globally unless explicitly intended. This approach helps prevent name conflicts and encourages better organization of code.Modules allow you to define
6 min read
How to create a private variable in JavaScript ? 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 vari
3 min read
Reference and Copy Variables in JavaScript In this article, we will talk about pass-by-value and pass-by-reference in JavaScript. JavaScript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the data. JavaScript has 5 primitive data types that are passed by value, they are Boolean, NULL, u
5 min read
Lexical Scope in JavaScript Lexical scope is a fundamental concept in programming that determines the accessibility of variables and functions based on where they are defined in the source code. In simple terms, lexical scope is the scope of a variable or function determined at compile time by its physical location in the code
4 min read
Private & Protected Constructors in TypeScript Constructors are important in creating objects within classes while using TypeScript, in this by default constructors are public and thus can be called from any location. At times though, you may want to stop any other person from creating instances of your class - that is where we come across priva
4 min read