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.
- In line 2, a variable named
undefined
is declared and has been initialized with a value1
. Yes I know what you are thinking now. Can we declareundefined
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.
- And in line 4, we are just checking the condition with the argument passed in the function.
- At line 7, we are alerting the value that is passed as an argument to the function
isDefined
. We expect it astrue
because a variable is defined withundefined
and it has value1
which is not equal toundefined
which is passed as an argument through the function. But the result isfalse
. What..? Why is that? Because, when you writeundefined
in a JavaScript program, you actually refer to a previously bound name. By default this will result in looking up the nameundefined
on the global object, which is what most people expect. - 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
.
Best Open Source Business Intelligence Software Helical Insight is Here
A Business Intelligence Framework
By
Uma Maheswar
Another suggestion is to use
return typeof x !== “undefined”;