I have a good grasp on the difference between undefined and null and the fact that JavaScript casts just about anything to a boolean, in particular, null to false.
My question is this: Why is the second alert triggered in both FF 9 and IE 9? (This is a small test script that is based on much more complex script. It is meant only to illustrate the issue…)
I’m expecting the . operator to take precedence and the expression to return null, which would then be cast to a boolean value of false. Adding parenthesis, !(context.isNull), makes no difference.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
</head>
<body>
<script type="text/javascript">
var context = this;
var isNull = null;
var aFunc = function() {
alert(context.isNull);
if (!context.isNull) {
alert("Is !context.isNull really true?");
}
};
aFunc();
</script>
</body>
</html>
First, “Thank you!” to everyone who responded.
I’m deeply embarrassed. It was late Friday on a long day, and I inverted the logic in my head. It is doing exactly what it should. The problem was that the actual code was checking for something existing, and I wrote my test case backwards.
What happens is that null is cast to false, !false is true, so the “if” code is executed. My (brain dead) choice of field names obscures the problem.
The reason for
is that the real code sits inside a constructor. The field “context” is then “closed” when the function is created, which preserves a reference to the object being constructed. This is important when the function is attached to another object (generally as an event handler), so that the function body can access the contents of the original object. Of course, in the example, “this” refers to the global object, which doesn’t serve much purpose.