You can do it, but the downside is that it can't be part of the prototype:

function Restaurant() {
    var myPrivateVar;

    var private_stuff = function() {  // Only visible inside Restaurant()
        myPrivateVar = "I can set this here!";
    }

    this.use_restroom = function() {  // use_restroom is visible to all
        private_stuff();
    }

    this.buy_food = function() {   // buy_food is visible to all
        private_stuff();
    }
}
Answer from 17 of 26 on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Classes › Private_elements
Private elements - JavaScript | MDN
A property in JavaScript has a string or symbol key, and has attributes like writable, enumerable, and configurable, but private elements have none. While private elements are accessed with the familiar dot notation, they cannot be proxied, enumerated, deleted, or interacted with using any Object method. ... class ClassWithPrivate { #privateField; #privateFieldWithInitializer = 42; #privateMethod() { // …
Top answer
1 of 16
455

You can do it, but the downside is that it can't be part of the prototype:

function Restaurant() {
    var myPrivateVar;

    var private_stuff = function() {  // Only visible inside Restaurant()
        myPrivateVar = "I can set this here!";
    }

    this.use_restroom = function() {  // use_restroom is visible to all
        private_stuff();
    }

    this.buy_food = function() {   // buy_food is visible to all
        private_stuff();
    }
}
2 of 16
226

Using self invoking function and call

JavaScript uses prototypes and does't have classes (or methods for that matter) like Object Oriented languages. A JavaScript developer need to think in JavaScript.

Wikipedia quote:

Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; when a function is called as a method of an object, the function's local this keyword is bound to that object for that invocation.

Solution using a self invoking function and the call function to call the private "method" :

var MyObject = (function () {
    
  // Constructor
  function MyObject(foo) {
    this._foo = foo;
  }

  function privateFun(prefix) {
    return prefix + this._foo;
  }
    
  MyObject.prototype.publicFun = function () {
    return privateFun.call(this, ">>");
  }
    
  return MyObject;

}());
var myObject = new MyObject("bar");
myObject.publicFun();      // Returns ">>bar"
myObject.privateFun(">>"); // ReferenceError: private is not defined

The call function allows us to call the private function with the appropriate context (this).

Simpler with Node.js

If you are using Node.js, you don't need the IIFE because you can take advantage of the module loading system:

function MyObject(foo) {
  this._foo = foo;
}
    
function privateFun(prefix) {
  return prefix + this._foo;
}

MyObject.prototype.publicFun = function () {
  return privateFun.call(this, ">>");
}
    
module.exports= MyObject;

Load the file:

var MyObject = require("./MyObject");
    
var myObject = new MyObject("bar");
myObject.publicFun();      // Returns ">>bar"
myObject.privateFun(">>"); // ReferenceError: private is not defined

(new!) Native private methods in future JavaScript versions

TC39 private methods and getter/setters for JavaScript classes proposal is stage 3. That means any time soon, JavaScript will implement private methods natively!

Note that JavaScript private class fields already exists in modern JavaScript versions.

Here is an example of how it is used:

class MyObject {

  // Private field
  #foo;
    
  constructor(foo) {
    this.#foo = foo;
  }

  #privateFun(prefix) {
   return prefix + this.#foo;
  }
    
  publicFun() {
    return this.#privateFun(">>");
  }

}

You may need a JavaScript transpiler/compiler to run this code on old JavaScript engines.

PS: If you wonder why the # prefix, read this.

(deprecated) ES7 with the Bind Operator

Warning: The bind operator TC39 proposition is near dead https://github.com/tc39/proposal-bind-operator/issues/53#issuecomment-374271822

The bind operator :: is an ECMAScript proposal and is implemented in Babel (stage 0).

export default class MyObject {
  constructor (foo) {
    this._foo = foo;
  }

  publicFun () {
    return this::privateFun(">>");
  }
}

function privateFun (prefix) {
  return prefix + this._foo;
}
Discussions

ES6 Class - How to write private method?
Hi, I completed the Binary Search Tree challenge… I used ES6 syntax. I am very nooby about Classes… This is the first time when I used. My question is: I made some method what only help to resolve the challenge: Exa… More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
5
0
December 3, 2019
What is the best practice for private properties in JS classes?
I would like to be able to create some classes that cannot have their properties modified from outside the class - instead only accessed or modified by class the functions. Yup, that's what private properties (with the hash #) are for. And they are technically fairly new, though many engines have supported them years before they were officially part of the language specification (ES2022). If you are worried about compatibility, you can always use something like babel to convert your source code into something more compatible before deploying. It will remove the private variables and replace them with something that would act the same way (though using a more convoluted approach). More on reddit.com
🌐 r/learnjavascript
8
2
November 15, 2022
Creating Private Methods in JavaScript Classes
In JavaScript, to build a class containing a public method, I can use the following approach: function Cafe() {} Cafe.prototype.order_drink = function() { // implementation here }; Cafe.prototype.visit_toilet = function() { // implementation here }; With this setup, users can interact with ... More on community.latenode.com
🌐 community.latenode.com
0
0
January 5, 2025
How do you deal with "private" methods?
The common JavaScript convention is to use an underscore prefix. var obj = { publicMethod: function() { ... }, _privateMethod: function() { ... } }; In ES6 you can also use symbols which are a lot harder, but not impossible (via Object.getOwnPropertySymbols()), to get to externally. But these also complicate subclassing a bit. I would go with underscores. More on reddit.com
🌐 r/javascript
13
1
October 16, 2016
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript private methods
JavaScript Private Methods
October 6, 2023 - Private methods can be called inside the class, not from outside of the class or in the subclasses.
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
ES6 Class - How to write private method? - Curriculum Help - The freeCodeCamp Forum
December 3, 2019 - Hi, I completed the Binary Search Tree challenge… I used ES6 syntax. I am very nooby about Classes… This is the first time when I used. My question is: I made some method what only help to resolve the challenge: Examples: levelOrder() reverseLevelOrder() These methods do the same, only with a little different (the directions) So I wrote another method: bfs() What is the correct syntax (or code) to turn private the bfs() method?
🌐
SitePoint
sitepoint.com › blog › es6 › javascript’s new private class fields, and how to use them
JavaScript's New Private Class Fields, and How to Use Them — SitePoint
November 13, 2024 - Private fields are used to store data that is only accessible within the class, while private methods are functions that can only be called from within the class. Private class fields are a relatively new feature in JavaScript, and as such they ...
🌐
Reddit
reddit.com › r/learnjavascript › what is the best practice for private properties in js classes?
r/learnjavascript on Reddit: What is the best practice for private properties in JS classes?
November 15, 2022 -

Hey folks I was just researching how to have private properties for a class in JS. I found this article on mdn web docs which explains the # syntax (which I guess is relatively new?)

Is it good practice to use this? Any tips from seasoned devs? I would like to be able to create some classes that cannot have their properties modified from outside the class - instead only accessed or modified by class the functions.

Below I have provided an example class using this syntax which seems to work how I wanted it to.

MDN article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields

Pastebin example I just made: https://pastebin.com/5sarVgjw

Find elsewhere
🌐
Fireship
fireship.dev › javascript-private-and-public-class-fields
JavaScript Private and Public Class Fields
Historically in JavaScript, because we've lacked the ability to have truly private values, we've marked them with an underscore. ... In the example above, we're relying on the consumer of the Car class to get the car's mileage by invoking the getMilesDriven method.
🌐
Medium
patrickkarsh.medium.com › emulating-private-methods-in-javascript-4812eba19504
Emulating Private Methods in JavaScript | by Patrick Karsh | Medium
October 7, 2023 - In many object-oriented programming languages, “private” methods are employed to hide internal details of a class, allowing only publicly exposed methods and properties to be accessed from the outside. However, JavaScript, being a dynamic and unique language, lacks native private methods in the traditional sense.
🌐
Go Make Things
gomakethings.com › private-class-features-in-vanilla-js-classes
Private class features in vanilla JS Classes | Go Make Things
July 20, 2022 - In a JavaScript class, you can prefix properties and functions with a hash (#) to denote them as private. They’re still attached to the prototype (or the constructor, if you use the static keyword), but cannot be accessed or run from outside ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Classes
Classes - JavaScript | MDN
May 22, 2026 - Private fields can only be declared ... to them, the way that normal properties can. Private methods and accessors can also be defined using the same syntax as their public counterparts, but with the identifier starting with #....
🌐
web.dev
web.dev › learn › javascript › classes › class-fields
Class fields and methods | web.dev
A private field must be declared in the body of the containing class. You can alter its value later as a property of this, but you can't create the field using this. Private fields can't be accessed from elsewhere in a script.
🌐
W3Schools
w3schools.com › js › js_classes.asp
JavaScript Classes
If you do not define a constructor method, JavaScript will add an empty constructor method. Class methods are created with the same syntax as object methods.
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › classes
Private and protected properties and methods
June 18, 2021 - In JavaScript, there are two types ... Until now we were only using public properties and methods. Private: accessible only from inside the class....
🌐
TypeScript
typescriptlang.org › docs › handbook › 2 › classes.html
TypeScript: Documentation - Classes
z);Property 'z' is private and ... 'z' is private and only accessible within class 'Params'.Try ... Class expressions are very similar to class declarations. The only real difference is that class expressions don’t need a name, though we can refer to them via whatever identifier they ended up bound to: ... JavaScript classes are instantiated with the new operator. Given the type of a class itself, the InstanceType utility type models this operation. ... Classes, methods, and fields ...
🌐
Codedamn
codedamn.com › news › javascript
What are Private Members in ES6 Classes?
October 18, 2023 - Here, constructor is a special method for creating and initializing objects created from a class. Methods, like greet, are added to the prototype chain. In OOP, encapsulation is crucial for bundling data (attributes) and methods that operate on that data into a single unit, as well as restricting direct access to some of an object’s components. This is where public and private members come in. Before ES6, JavaScript developers had to employ strategies like closures and the Module Pattern to mimic the behavior of private members.
🌐
Code with Jason
codewithjason.com › home › the purpose of private methods and when to use them
The purpose of private methods and when to use them - Code with Jason
October 5, 2021 - Private methods have too many dependencies because they directly access or modify internal state · Both the above arguments could apply just as much to public methods. Public methods could indicate the class is doing too many things.
🌐
Educative
educative.io › answers › how-to-create-a-private-method-of-a-class-in-javascript
How to create a private method of a class in JavaScript?
Our private method can be declared by adding the # before the method name. ... Line 6: We have created a new class with the name ClassWithPrivateMethod.
🌐
Latenode
community.latenode.com › other questions › javascript
Creating Private Methods in JavaScript Classes - JavaScript - Latenode Official Community
January 5, 2025 - In JavaScript, to build a class containing a public method, I can use the following approach: function Cafe() {} Cafe.prototype.order_drink = function() { // implementation here }; Cafe.prototype.visit_toilet = function() { // implementation here }; With this setup, users can interact with my class like this: var cafe = new Cafe(); cafe.order_drink(); cafe.visit_toilet(); I’m looking for guidance on how to establish a private method that can only be accessed by the order_drink and vi...
🌐
DEV Community
dev.to › smitterhane › private-class-fields-in-javascript-es2022-3b8
Private class fields in Javascript (ES2022) - DEV Community
July 17, 2022 - Class fields and class methods are public by default. It is common you may want to make your class fields private. If you come from a Java background, you may achieve this with the private keyword inside of a Java class definition. JavaScript has lacked such a feature since its inception.
🌐
Medium
eisenbergeffect.medium.com › public-private-and-protected-class-visibility-patterns-in-javascript-a23a29229430
Public, Private, and Protected Class Visibility Patterns in JavaScript | by EisenbergEffect | Medium
October 3, 2023 - Fields, getters, setters, and methods, both instance and static, can all be made private, with one exception: constructors cannot be made private. However, there is a pattern you can use to prevent unauthorized calls to a constructor.