When we are working with JavaScript operators, we need to pay utmost attention on how we use them. For example let’s create a simple function which takes two arguments a, b.

function foo(a, b) {
    a = a || "value";
    b = b || 4;
    
    alert("a is: "+ a + "; b is: " + b);
}

foo("", 0);


Stop..!! Don’t jump on the result. Go through the function and what has been passed as arguments to the function. Now if your answer is 0 then you are wrong. Rather you get a is: value; b is 4. Wait. What? Why is that? In JavaScript, we need to verify whether passed arguments are of valid inputs are not. Certainly, empty string isn’t a valid input and 0 isn’t too. Hence we get the result that we didn’t expect.

Let us go on something which is much more interesting. Suppose I have this code written:

1: var isDefined = function () {
2:     var undefined = 1;
3:     return function (x) {
4:         return x !== undefined;
5:     };
6: }();

7: alert(isDefined(undefined));
8: alert(isDefined(1));


So what does the above alerts return? Before that, let us first go through each line of code that is written.

  1. In line 2, a variable named undefined is declared and has been initialized with a value 1. Yes I know what you are thinking now. Can we declare undefined as a variable? And the answer is Yes. We can.!! undefined is not a JavaScript keyword. Rather, it can be specified as:

    The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined.

  2. And in line 4, we are just checking the condition with the argument passed in the function.
  3. At line 7, we are alerting the value that is passed as an argument to the function isDefined. We expect it as true because a variable is defined with undefined and it has value 1 which is not equal to undefined which is passed as an argument through the function. But the result is false. What..? Why is that? Because, when you write undefined in a JavaScript program, you actually refer to a previously bound name. By default this will result in looking up the name undefined on the global object, which is what most people expect.
  4. Now what will line 8 alert? Obviously true.


So how can we fix this? If you get it right, you should stat using void 0 which always yields the undefined value. Now rewrite the function as shown below:

1: var isDefined = function () {
2:     var undefined = 1;
3:     return function (x) {
4:         return x !== void 0;
5:     };
6: }();

7: alert(isDefined(undefined));
8: alert(isDefined(1));


Now line 7 alerts true as expected and line 8 alerts false.

By
Uma Maheswar

1 comment

  1. Zvi Landsman

    Another suggestion is to use

    return typeof x !== “undefined”;

Leave a Reply