2
if (typeof operand1 != "undefined" && operand1 == operand2) {
}

Above is an if statement that checks for the equality between operand1 and operand2, where operand1 may be undefined under some scenario. I wonder if the typeof operand1 != "undefined" is unnecessary.

tamakisquare
  • 16,659
  • 26
  • 88
  • 129

2 Answers2

3

Because you use the == operator and not the === operator, it's unnecessary only if operand2 will never be null.

But you can change the if statement to use the === operator which then will pass only if operand2 "really equals" to operand1, meaning operand2 is undefined as well.

You can read more about it here:
Which equals operator (== vs ===) should be used in JavaScript comparisons?

A fiddle that shows what was written here.


In the Data Baseworld, null(or undefined) is nothing, which means you can't compare it to anything.

SQL example:

SELECT *
FROM   table_name t
Where  t.operand1 = null

is an error because nothing equals to null, and null doesn't equal to anything, it just doesn't exist.

In javascript it is not like that, you can compare things to null and undefined, but you have to be careful with TypeErrors, like with this:

var x;
x.foo; // TypeError!
Community
  • 1
  • 1
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • Your last example is incorrect. It would be `TypeError`, as `undefined` does and can not have properties. – alex Apr 10 '12 at 23:03
  • @gdoron can you please elaborate on what you mean by "it's unnecessary only if operand2 will never be a falsy value"? Say operand2 can be a falsy value, I would like to see an example where 'typeof operand1 != "undefined"' is necessary. Thx – tamakisquare Apr 11 '12 at 18:33
  • @ahmoo. There was a little mistake in the answer, I fixed it. anyway you can see an example in the DEMO I added to my answer. Is it clear now? – gdoron Apr 11 '12 at 19:26
  • 1
    @gdoron - yes, the example and your further explanation have made everything clear now. Thanks. Much appreciated. – tamakisquare Apr 11 '12 at 20:00
2

The only time I'd say it's necessary to do that typeof check before checking the equality of two variables' values is when one of them (operand1) may not be defined, preventing a ReferenceError.

jsFiddle.

alex
  • 479,566
  • 201
  • 878
  • 984
  • 2
    @gdoron I didn't say `undefined`, I said *not defined*, as in, there is no variable named `operand1` in the scope chain. – alex Apr 10 '12 at 22:56
  • Thanks for your answer. You have brought up a good point. I only wish I could accept more than one answer. – tamakisquare Apr 11 '12 at 20:10
  • I think there's a typo in your fiddle. It would still get ReferenceError even if `typeof operand1 != "undefined"` is there. – tamakisquare Apr 11 '12 at 20:30
  • @ahmoo The fiddle was to demonstrate the `ReferenceError`. Try uncommenting out the bits I commented. – alex Apr 11 '12 at 22:04