Radu Radu - 7 months ago 7
Javascript Question

Why is 1 == '1\n' true in Javascript?

The same goes for

'1\t'
(and probably others).

if (1 == '1\n') {
console.log('Equal');
}
else {
console.log('Not Equal');
}

Answer

As said before if you compare number == string, it will automatically try to convert the string to a number. the \n and \t are simply whitespace characters and therefore ignored.

This and similar behaviour can be rather confusing leading to situations like this:

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

Comments