Page 1 of 2
For example, the humble and over-worked string literal is an object complete with methods and properties. For example:
displays 4. This almost seems against the laws of programming when you first see it but yes raw data in the form of a quoted string is an example of a string object and has the methods and properties of a string object.
With this in mind consider the following simple function that tests to see if a string is equal to a target string literal:
Notice that this is an exact test. That is, s has to be equal to "Yes" and not convertible to "Yes" from some other data type. In this case using either == which is a looser test for equality, or using === which is strict equality doesn't seem to be a big issue. After all a string is either a string or it isn't and it is either equal to "Yes" or it isn't. So you could use:
just as easily and expect to get the same results. But it it is generally held (for example JSLint) that you should avoid == and != so the first function is the one that was used.
The utility function was used as part of a much larger program and eventually a bug was tracked down to it sometimes returning false when the string passed to it was indeed "yes".
The function was carefully checked and two debugging commands added:
so that the value of s could be seen along with the result. During one run the function returned:
That is, the parameter passed in stored "yes" and the result of the comparison s==="yes" was false.
This cannot be!
What is going on?
Turn to the next page when you are ready to find out.