Design & Download
Your JS Library
in Seconds!!!

Snippet: get() & set()

Written by Christopher West (cwest) on November 08, 2015.
Get and/or set values in an object.
function get(obj, propName, opt_defaultValue) {
  return has(Object(obj), propName) ? obj[propName] : opt_defaultValue;
}

function set(obj, propName, value) {
  var prev = obj[propName];
  obj[propName] = value;
  return this instanceof YourJS ? obj : prev;
}

One of the fundamentals of object-oriented programming is getters and setters. Getters and setters can make it easier to modify objects:

var me = {
  first_name: 'Chris',
  last_name: 'North'
};

YourJS.set(me, 'last_name', 'West');  // Returns "North"
console.log('First Name:', YourJS.get(me, 'first_name'));
console.log('Last Name:', YourJS.get(me, 'last_name'));

Using these two functions along with YourJS.partial() and YourJS.rearg() we can create property specific getters and setters for any object:

var me = {
  first_name: 'Chris',
  last_name: 'North'
};
var getFirstName = YourJS.partial(YourJS.rearg(YourJS.get, 1, 0), 'first_name');
var getLastName = YourJS.partial(YourJS.rearg(YourJS.get, 1, 0), 'last_name');

console.log('First Name:', getFirstName(me));
console.log('Last Name:', getLastName(me));

YourJS.get(obj, propName, opt_defaultValue) API Documentation

Parameters

  1. obj {Object}:
    The object whose property will be retrieved.
  2. propName {string}:
    The name of the property to be retrieved.
  3. opt_defaultValue {*}:
    Optional. The default value to return if obj[propName] wasn't ever defined.

Returns

Returns obj[propName] if it was defined, otherwise returns opt_defaultValue.

YourJS.set(obj, propName, value) API Documentation

Parameters

  1. obj {Object}:
    The object whose property will be modified.
  2. propName {string}:
    The name of the property to be modified.
  3. value {*}:
    The value to assign to obj[propName].

Returns

Returns the previous value of obj[propName].