Javascript Getter/Setter Function for Private Variables

Working on an angular project I found the need to make some private variables for my services. I have used the pattern of making an object that is returned.

The private nature of the variable was achieved by creating a variable in main function and returning a service object.

I wanted to allow you to call the method without an argument to get the current value and passing an argument would set and return the value.

First Version

(function() {
  "use strict";

  angular.module('app')
    .service('MyService',[function() {
      //status acts like a private value
      var status = false;

     //the service is returned
      var service = {
        status:  function(new_status) {
          if(new_status > 1) {
            status = new_status;
          }
          return status;
        }
      };
      return service;
    }]);

})();

This worked fine until I needed to set the status to a null or false value. To get around this I updated the code to check the magic arguments variable. All functions have a variable named arguments that contain details about the arguments passed in.

Final Version

(function() {
  "use strict";

  angular.module('app')
    .service('MyService',[function() {
      //status acts like a private value
      var status = false;

     //the service is returned
      var service = {
        status:  function(new_status) {
          if(arguments.length > 1) {
            status = new_status;
          }
          //do some other stuff here based on the status
          return status;
        }
      };
      return service;
    }]);

})();

Using the code

MyService.status() # returns false  
MyService.status('pending') #sets and returns pending  
MyService.status() # returns pending  
MyService.status(false) # sets and returns false  
MyService.status() #returns false