Why is there 1 == '1 \ n' true in JavaScript?

The same applies to '1\t'(and possibly others).

if (1 == '1\n') {
  console.log('Equal');
}
else {
  console.log('Not Equal');
}
0
source share
2 answers

As already mentioned, if you compare number == string, it will automatically try to convert the string to a number. \nand \tare just whitespace characters and therefore are ignored.

This and similar behavior can be quite confusing, leading to the following situations:

(Image taken from: https://www.reddit.com/r/ProgrammerHumor/comments/3imr8q/javascript/ )

+2
source

(==) , , . , JavaScript , , .

1 Number, '1\n' Number, comparison!

Number() ('1\n') 1: -

Number('1\n') === 1

Strict equality using ===, - . , .

, 1 === '1\n' false

+2

Source: https://habr.com/ru/post/1690866/


All Articles