0

The following code works fine:

    var styles = []
    if (state == 's1') {
        styles = ['inline-block', 'none', 'none']
    } else if (state == 's2') {
        styles = ['none', 'inline-block', 'none']
    } else if (state == 's3') {
        styles = ['none', 'none', 'inline-block']
    }

However in some languages we can make this more concise. I would like to do something along the following lines:

    var styles = 
      if (state == 's1') {
          ['inline-block', 'none', 'none']
      } else if (state == 's2') {
          ['none', 'inline-block', 'none']
      } else if (state == 's3') {
          ['none', 'none', 'inline-block']
      }

Is there such a conditional assignment - or even better some kind of match/case - in javascript?

Update Lots of good answers - thanks! Chose one seems closest to my original intent. But learnt a variety of aspects of javascript across many of them.

1
  • The closest i could think of would be ternary operator, but it's far from elegant. Commented Jan 27, 2020 at 17:30

7 Answers 7

2

You can define the conditions as a function

chooseStyle = (state) => {
    if (state == 's1') {
        return ['inline-block', 'none', 'none']
    } else if (state == 's2') {
        return ['none', 'inline-block', 'none']
    } else if (state == 's3') {
        return ['none', 'none', 'inline-block']
    }
}

var styles = chooseStyle(state)

Or even better if you use a switch instead:

chooseStyle = (state) => {
    switch(state) {
        case 's1':
            return ['inline-block', 'none', 'none']
        case 's2':
            return ['none', 'inline-block', 'none']
        case 's3':
            return ['none', 'none', 'inline-block']
        default:
            return ['inline-block', 'none', 'none'] // return the default styles you want, here I choose the styles of 's1'
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

You function does not returns anythings. The result will always be undefined.
This looks so far actually closest to my original intent
2

You could take an array of states and map either 'inline-block' for a value at this index or 'none'.

const
    order = ['s1', 's2', 's3'],
    getStyles = state => order.map(v => v === state ? 'inline-block' : 'none');

console.log(...getStyles('s1'));
console.log(...getStyles('s2'));
console.log(...getStyles('s3'));

3 Comments

Not sure how the v === state makes this work - can you elaborate?
v is an item of order and if the value at this position is the wanted one, then it takes 'inline-block' or 'none' by using a conditional (ternary) operator ?:.
ah got it: i was not thinking along collections manipulation lines
1

Like many languages whose syntax is patterned after C, JavaScript has conditional expressions (aka "tertiary") that can be used for simple if-then-else conditions.

condition ? true-value : false-value

You can nest these for multiple cases, but it tends to become unreadable.

var styles = state == 's1' ? ['inline-block', 'none', 'none'] :
    (state == 's2' ? ['none', 'inline-block', 'none'] : ['none', 'none', 'inline-block']);

There's no analogous expression form of case. But you could use an object:

const style_mappings = {
    "s1": ['inline-block', 'none', 'none'],
    "s2": ['none', 'inline-block', 'none'],
    "s3": ['none', 'none', 'inline-block']
};
var styles = style_mappings[state];

Comments

1

Use a mapping object:

const styleMap = {
  s1: ['inline-block', 'none', 'none'],
  s2: ['none', 'inline-block', 'none'],
  s3: ['none', 'none', 'inline-block'],
};

const styles = styleMap[state];

Comments

1

JavaScript doesn't have anything exactly like that, but one solution which gets pretty close is to store the results in an object/dictionary and call it with the state you want:

const styles = {
  's1': ['inline-block', 'none', 'none'],
  's2': ['none', 'inline-block', 'none'],
  's3': ['none', 'none', 'inline-block']
}
console.log(`s1: ${styles['s1']}`)
console.log(`s2: ${styles['s2']}`)
console.log(`s3: ${styles['s3']}`)

Comments

0

You could use the switch statement in JavaScript to accomplish this. Your code would be something like this

var styles = ['none', 'none', 'none'];
switch (state) {
    case 's1':
        styles[0]='inline-block';
        break;
    case 's2':
        styles[1]='inline-block';
        break;
    case 's3':
        styles[2]='inline-block';
        break;
}

1 Comment

That still has multiple explicit assignments .
0

You could use a tenary javascript operator. So the code may look like so:

var styles = (state == 's1')? 
                        ['inline-block', 'none', 'none']:  (state == 's2')? 
                                                            ['none', 'inline-block', 'none']: (state == 's3')?
                                                                                              ['none', 'none', 'inline-block']:[]; 

Usage example:

Example 1:
var state = 's1'; 
console.log(styles);  //outputs [ "inline-block", "none", "none" ]
Example 2: 
var state = 's2'; 
console.log(styles);  //outputs [ "none", "inline-block", "none" ]
Example 3: 
var state = 's3'; 
console.log(styles);  //outputs [ "none", "none", "inline-block" ]
Example 4: 
var state = 's'//a state without a match
console.log(styles);  //outputs []

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.