Why does this code always return False?

Asked

Viewed 41 times

2

Can anyone explain to me why it always returns false????

function ValidationProcessDoc( ext ){
    if ( ext === 'TXT' || 'DOC' || 'XLS' || 'PPT' ) {
        return false;
    }
    else if ( ext === 'PDF' || 'HTM' || 'HTML' ) {
        console.log(ext);
        return true;
    }
    else {
        return false;
    }
}

1 answer

2


It always returns false, because the first condition will always be true, regardless of the parameter you pass.

This happens on account of the following check:

if ( ext === 'TXT' || 'DOC' || 'XLS' || 'PPT' ) {

If the value of ext is different from 'TXT', all other conditions are true, because javascript understands that a non-empty string is true, see this example:

if ("Teste") {
  console.log("(\"Teste\") = Verdadeiro");
}

if ("") {
  console.log("(\"\") = Verdadeiro");
}

Understand that if I make one if using a string with value, the condition is met.


If you want to fix your code simply, do the other checks using the variable ext again:

function ValidationProcessDoc( ext ){
  if ( ext === 'TXT' || ext === 'DOC' || ext === 'XLS' || ext === 'PPT' ) {
      return false;
  }
  else if ( ext === 'PDF' || ext === 'HTM' || ext === 'HTML' ) {
      return true;
  }
  else {
      return false;
  }
}

console.log( ValidationProcessDoc('PDF') );
console.log( ValidationProcessDoc('TXT') );
console.log( ValidationProcessDoc('XISTO') );


You can change its function, making it much simpler, directly return the check of the returning types true:

function ValidationProcessDoc( ext ){
  return ext === 'PDF' || ext === 'HTM' || ext === 'HTML';
}

console.log( ValidationProcessDoc('PDF') );
console.log( ValidationProcessDoc('TXT') );
console.log( ValidationProcessDoc('XISTO') );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.