Object’s private variable

What is meant by private variable in this context:

Getter functions are meant to simply return (get) the value of an object’s private variable to the user without the user directly accessing the private variable.

Setter functions are meant to modify (set) the value of an object’s private variable based on the value passed into the setter function. This change could involve calculations, or even overwriting the previous value completely.

In this note it is been said that the practice of preceding the name of a variable with an underscore doesn’t make it private, then how to make a variable private?

Note: It is convention to precede the name of a private variable with an underscore ( _ ). However, the practice itself does not make a variable private.

Challenge: Use getters and setters to Control Access to an Object

Link to the challenge:

There are two ways to work with that. One, javascript does support private properties, with something like 94% of modern browsers handling them. You can learn about them on Mozilla: Working with private class features - JavaScript | MDN

And yes, getters and setters are a good way of working with those private properties. But that isn’t the same as a private variable. Properties are on an object, while variables are in a function (or block) scope.

For private variables, we might look at closures, and factory functions. https://www.freecodecamp.org/news/javascript-create-object-how-to-define-objects-in-js/amp/

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.