True but not true
Written by Ian Elliot   
Article Index
True but not true
Solution

The way that JavaScript deals with (or rather doesn't deal with) types can cause programmers at all levels to come unstuck.

 

Banner

Background

JavaScript is a wonderful language but sometimes it suffers from trying too hard to be easy for beginners to use. Often it isn't the beginner who comes unstuck but the more advanced programmer who has forgotten the strange ways of JavaScript and expects it to be reasonable. 

The source for this problem is the way JavaScript tries to be typeless and coerces data to be a type that makes sense in the given context. Once again you could say that this is a bad thing and JavaScript should give control of type conversion to the programmer but this is too easy. In a type free language you have to allow some automatic conversion to and between primitive types if you want the language to be easy to use.

The problem is that doing it correctly is a difficult task and JavaScript only gets it partly right. This doesn't mean that it can't be done in a sensible and consistent way. But until that day it will be a valuable source of Programmer Puzzles!

 

Banner

Puzzle

As with all our puzzles this one has been stripped down to its essentials. In the real code the situation was much more complicated and it was much harder to see what was going on.

In this case the problem all started with a little refactoring - as it often does. The original code was a simple if with two options - represented here by alerts:

if(flag)
{
alert("true");
}else(
alert("false")
);

The setting of the flag variable, clearly expected to be a Boolean was in the test case true as proved by the fact that the alert box popped up and displayed "true".

For reasons of aesthetics the programmer in question didn't like the idiom 

if(flag)

and preferred

if(flag==true)

The change was duly made to give:

if(flag==true)
{
alert("true");
}else(
alert("false")
);

All should be good but the same test case applied to the code produced an alert box which displayed "false".

Immediately the suspicion fell on the use of the == inexact equality operator but when the program was changed to

if(flag===true)
{
alert("true");
}else(
alert("false")
);

it produced the same behavior.

What is going on?

How can if(flag) be true and if(flag===true) be false?

This seems like an odd way to do logic!

 

Turn to the next page when you are ready to find out.

<ASIN:0596805527>

<ASIN:0470684143>

<ASIN:0137054890>

<ASIN:0596517742>