if statements and return var === somethingElse

87 views Asked by At

I'm doing the Angular course on codeschool and passed one of the exercises by doing:

this.isSet = function(value) {
  if (value === this.tab) {
    return true;
  }
};

But in the next exercise, my code gets replaced by this:

this.isSet = function(tabName){
  return this.tab === tabName;
};

This must be a silly question, but can you bypass an if statement by just using a simple === ?

3

There are 3 answers

0
Lauri Elias On

if value === this.tab, true will be returned, if value !== this.tab, undefined will be returned. In the second example === will return true and !== will return false. Undefined and false are both 'falsy', therefore you can use them in much the same way.

1
Oskar Lindberg On

If you re-read your own code you'll see that the if statement does not add anything, and that if it fails, your function will return undefined, which is not optimal, as it's not a boolean value.

It's not a "bypass" (I don't quite understand what you mean by that), but the statement return this.tab === tabName; returns true or false depending on the evaluation result (which will always be a boolean value. I.e. the second code example returns the same value (true) as the first, when the values of value/tabName and this.tab respectively are equal (===).

0
Santosh Panda On

The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. It's this case where === will be faster, and may return a different result than ==. In all other cases performance will be the same.

See this tutorial for more details: http://www.c-point.com/javascript_tutorial/jsgrpComparison.htm