Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a variable contain a switch of function?

Tags:

javascript

I've been googling my little heart out, but I either am asking the wrong question, or it's so obscure it doesn't exists. What I would like to know is can you define a variable with a switch inside it. Things to note about my knowledge of programing and on what level I would understand your answer. I'm a graphic/web designer with only a little experience in js.

Something like this...

var variable = {
    switch (case) {
      case 'case1':
        return "something";
      case 'case2':
        return "something";
      case 'case3':
        return "something";
    };
  };

I know I could just make the switch separate and set the variable per case, but I'm just wondering if this can be done. Also can functions be inside variables? And, how would it be done? Would it be inefficient?

like image 546
Ryan Lutz Avatar asked Feb 19 '26 14:02

Ryan Lutz


1 Answers

You will sometimes see object literals used in place of switch statements. For example, the following hypothetical syntax:

var variable = {
  switch (switchOver) {
    case 'case1':
      return 'something1';
    case 'case2':
      return 'something2';
    case 'case3':
      return 'something2';
  };
};

Can be actually written like this:

var variable = {
  'case1': 'something1',
  'case2': 'something2',
  'case3': 'something3'
}[switchOver];

Which is just a shorthand notation for this:

var cases = {
  'case1': 'something1',
  'case2': 'something2',
  'case3': 'something3'
};

var variable = cases[switchOver];
like image 105
Ionuț G. Stan Avatar answered Feb 21 '26 04:02

Ionuț G. Stan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!