Impossible Equalities - a JavaScript puzzle |
Written by Ian Elliot | |||
Page 1 of 2 It is almost folklore that the JavaScript equality operator == is evil and you should always use the strict equality operator === but sometimes it just makes things easier to get JavaScript to do all of the conversions for you. In this puzzle the temptation leads to a real problem. One of the really nice things about JavaScript from the beginner's point of view is that it will automatically do type conversion for you. This means you really don't have to worry too much about whether a number is in numeric form or string form; you can just use it. Of course, when you learn a little more about data types and how they can be used to ensure program correctness, the temptation is to mark it as evil. While it is true that auto-type conversion or type juggling can lead to serious errors, it is important not to simply dismiss its use - it can be helpful and it can be reasonably safe as long as you understand how it all works. In the spirit of trying to foster understanding let's take a look at an interesting problem. BackgroundJavaScript attempts to be as data type independent as possible. This is a noble aim. If you really are going to try to get rid of data type from a language then you really do need to find ways of interpreting things like 1+"1" and 1=="1" and so on. In general, JavaScript will attempt to perform a type conversion to make an expression work rather than fail. However this doesn't always work in the way that an innocent beginner would expect. For example, 1+"1" doesn't evaluate to numeric 2 but to a string "11". However 1=="1" does evaluate to true, as you most likely already know. The problem is that even this simple equality test can go horribly wrong.
PuzzleThe task our novice programmer had to solve was checking that two variables were equal and doing something if they were. Later in the program each variable was tested for being a zero. The raw essence of the program was: if(a==b)alert("a equals b"); You can try alternative logical arrangements but this is arguably the simplest. This code worked perfectly for a while and then a problem came to light. The first statement displayed "a equals b" The second statement displayed "a is zero". The third statement did not display "b is zero" So a and b are not equal but a is zero and c is a zero! What is going on? What values of a and b behave like this? Turn to the next page when you are ready to find out.
<ASIN:0596805527> <ASIN:1449399029> <ASIN:0137054890> <ASIN:0596517742> |