1

After asking a few questions on here and confirming that js does not pass references, only values, the question becomes, how do you make dynamic decision making. Let me explain. Right now i use many switch statements in a complicated form i am creating. But i would like to create an array that has many objects that contain the condition to be met and the variable or function to execute. The way i achieve this right now is to name the variable in plain text and execute it in brackets like so: this[nameofvar] = false where 'nameofvar' is the string store in the array object. This to me is bad on so many level and hackish.

So how do you do it?

The Architect
  • 313
  • 2
  • 10
  • 1
    Using the [square bracket notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors) like you are doing is the correct way to do what you are asking. I'm not sure what about it you consider bad or hackish. Using dynamic property and method names this way could be considered bad if abused but the syntax itself is not bad or hackish. – Marty Aug 03 '17 at 01:42
  • Doesn't pass references? Since when? – Jared Smith Aug 03 '17 at 01:46
  • Also see [this question](https://stackoverflow.com/questions/13104494/does-javascript-pass-by-reference) for an in depth look at js passing by value/reference – sauntimo Aug 03 '17 at 01:56

1 Answers1

1

You could consider replacing your switch statement with an object literal. Take a look at this example written by Todd motto, taken from his article on this concept - I found this really helpful and I much prefer doing complicated conditional logic this way now.

note the way the methods are called: (obj[key] || obj['default'])(); ie, use the method defined by the key if it exists, or fall back to the default. So the first truthy value of the two is invoked (func)();.

function getDrink (type) {
  var drink;
  var drinks = {
    'coke': function () {
      drink = 'Coke';
    },
    'pepsi': function () {
      drink = 'Pepsi';
    },
    'lemonade': function () {
      drink = 'Lemonade';
    },
    'default': function () {
      drink = 'Default item';
    }
  };
    
  // invoke it
  (drinks[type] || drinks['default'])();
    
  // return a String with chosen drink
  return 'The drink I chose was ' + drink;
}

var drink = getDrink('coke');
// The drink I chose was Coke
console.log(drink);
sauntimo
  • 1,531
  • 1
  • 17
  • 28