Private Variables in Javascript

, ,

If you are writing code and you want a user to manipulate data using methods you create but also don’t want the user to be able to manipulate data directly. One way you can go about this is through functional programming. Say you want to have an object that has the ability to move right and left with a starting position at 0. You might build out something like this:

const walker = {
    position = 0,
    right: function() {
        this.position++
    },
    left: function() {
        this.position–
    }
}

Then you call the function, walker.right() to move right and walker.left() to move left. However the way this is set up, a person can redefine the position variable by just directly changing it I.e. walker.position = 20. This is not good because the walker will be teleporting without ever hitting positions 1-19. So how do you stop a user from directly changing a variable that you don’t want them to change. An easy way to make this a private variable, is to make a function that return an object with only the method you want them to use. For example:

function walker() {
    let position = 0,
    return {
        right: function() {
            this.position++
        },
        left: function() {
            this.position–
        }
    }
}

const ben = walker()
ben.right()

I made a new variable called “ben” from the walker function. The way this is set up a user can no longer directly change the position property.