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?

3
  • 1
    Using the square bracket notation 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. Commented Aug 3, 2017 at 1:42
  • Doesn't pass references? Since when? Commented Aug 3, 2017 at 1:46
  • Also see this question for an in depth look at js passing by value/reference Commented Aug 3, 2017 at 1:56

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.