1. Code
  2. Web Development

Quick Tip: Private Variables in JavaScript

Read Time:1 minLanguages:

Because of JavaScript's dependence upon globals, it might be easy to forget that creating private variables can be accomplished quite simply, thanks to closures. In just a few minutes, I'll demonstrate two common techniques which allow for private variables and methods in your projects.

The key to this particular method is to create a variable that is equal to the returned value of a function. That way, we can specifically choose with values and methods are available to our object. Thanks to closures, we'll still have access to these private variables, even after the object has been returned from our singleton.

View a live demo.

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.