Public 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:

public

Public, Private, and Protected Scope in JavaScript

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.

Table of Content

  • Private Scope
  • Public Scope
  • Protected Scope

Scopes

Similar Reads

Private 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....

Public Scope:

...

Protected 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....

Contact Us