0

For example, a have two statement conditions:

First, something similar to

const condition1 = value === '' && value1 === '' && value2 === '' && valu3e === '' && value4 === '' && value5 === ''

and second conditions more simple like

const condition2 = value === 'error'

and my if the statement has the two like this:

if (condition1 || condition2) {
....
}

Has any way to make this better than the actual implementation?

3
  • 5
    Do you really have 6 enumerated value variables? Use an array instead. Commented Dec 11, 2020 at 13:34
  • Extracting each logical expression result to a variable seems pretty good. It's the usual solution for having extremely big logical expressions. Is there a problem with using that? Commented Dec 11, 2020 at 13:35
  • Estou tentando extrair isso de cada lógica, mas fico errado em algo porque são mais de 6 expressões. Mas agora está tudo bem, obrigado pessoal. Commented Dec 14, 2020 at 17:27

2 Answers 2

2

First condition :

const value = '',
  value1 = '',
  value2 = '',
  value3 = '',
  value4 = '',
  value5 = '';

const condition1 = [
  value,
  value1,
  value2,
  value3,
  value4,
  value5,
].every(x => x === '');

console.log(`Condition1 : ${condition1}`);


If you can refactor the values to be an array it would be better.

const values = [
  '',
  '',
  '',
  '',
  '',
  '',
];

const condition1 = values.every(x => x === '');

console.log(`Condition1 : ${condition1}`);


Altogether

const value = '',
  value1 = '',
  value2 = '',
  value3 = '',
  value4 = '',
  value5 = '';
  
if ([
  value,
  value1,
  value2,
  value3,
  value4,
  value5,
].every(x => x === '') || value === 'error') {
  console.log(`Condition : true`);
} else {
  console.log(`Condition : false`);
}

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

Comments

1

why not simply :

if ( (value === '' && value1 === '' && value2 === '' && valu3e === '') 
   || value === 'error' 
   ) {
  /// ...
}

?

1 Comment

I using this, but the condition is more largest that from my question, because this I try to refactor her. But thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.