3

I want to know how I can avoid automatic coercion when comparing numbers using the less than and higher than operator in JavaScript.

For example, I already know that == operator makes type coercion, for example:

1 == '1'; //true

And === operator doesn't, for example:

1 === '1'; // false

But, how I can avoid this when comparing numbers?, for example:

1<2; //true
1<'2'; //true
1<'0'; //false

I want to avoid this automatic type coercion.

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
dseminara
  • 11,665
  • 2
  • 20
  • 22

1 Answers1

0

Use boxing via the RegExp literal. For example:

console.log(/3.1/ > 3);
console.log(/3.1/.exec(3.1) > 3)
console.log((/Infinity/).toString().replace(/\//g,"") > 3)

or NumberFormat:

console.log(new Intl.NumberFormat({}, {'style':'percent'}).format(2) > 1)

References

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265