Private and Protected Properties & Methods in JavaScript
In JavaScript, private and protected properties/methods help encapsulate class data, preventing direct modification from outside the class.
š¹ Private Properties and Methods (#
)
Private properties and methods can only be accessed inside the class where they are defined.
✅ Example: Private Property & Method (#
)
✔ #password
and #encryptPassword()
are private, so they cannot be accessed from outside the class.
✔ getEncryptedPassword()
provides a controlled way to access the encrypted password.
š¹ Protected Properties and Methods (_
Convention)
JavaScript does not have built-in protected properties like other languages.
However, the underscore _
naming convention is used to indicate that a property should be treated as protected.
✅ Example: Protected Property Using _
✔ _age
is not truly protected, but developers should treat it as "internal use only."
✔ Unlike private properties (#
), _age
can still be accessed and modified outside the class.
š¹ Private vs. Protected: Key Differences
Feature | Private (# ) | Protected (_ Convention) |
---|---|---|
Access from class | ✅ Allowed | ✅ Allowed |
Access from subclass | ❌ Not Allowed | ✅ Allowed |
Access from outside | ❌ Not Allowed | ⚠️ Technically possible but discouraged |
Real encapsulation? | ✅ Yes, enforced by JavaScript | ❌ No, just a naming convention |
šÆ Summary
✔ Private properties/methods (#
): Fully hidden, accessible only inside the class.
✔ Protected properties (_
): Accessible inside subclasses but not truly protected.
✔ Use private (#
) for strong encapsulation.
✔ Use protected (_
) if subclass access is needed, but follow conventions.
š Need more clarification? Let me know! š