-1

var x = 'x' 
x-'m'||console.log('True 1') 
// logs True, should be false

var x = '2' 
x-2||console.log('True 2') 
// logs True

var x = '3' 
x-2||console.log('True 3') 
// logs False

Why does this if else shorthand always return true when using a string? How can it be fixed?

I learnt this from here

VLAZ
  • 26,331
  • 9
  • 49
  • 67
jmenezes
  • 1,888
  • 6
  • 28
  • 44

1 Answers1

0

If the expression before the || returns a falsy expression, then the console.log() is executed. This happens for the first expression 'x' - 'm' which produces NaN (which is falsy):

console.log('x' - 'm')

and for the second expression '2' - 2 which returns 0 (which is falsy):

console.log('2' - 2)

Your console.log() does not get executed for the third expression '3' - 2 because that returns 1 (which is truthy):

console.log('3' - 2)
Peter B
  • 22,460
  • 5
  • 32
  • 69