0

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 === ?

user3697034
  • 127
  • 1
  • 1
  • 7
  • (x === y) is either true or false. The difference between the first and the second is that the second can also return false, if they are not equal – Ronni Skansing Nov 22 '14 at 12:35
  • No, the two things don't mean the same thing. Just think about it - a `return` always returns the expression, whereas a `return` wrapped in an if statement only returns when the if statement's body is executed. Otherwise, control flow would continue within the body of the function. – The Paramagnetic Croissant Nov 22 '14 at 12:35
  • I know programmers, who write even: `if(bool_var == true) {return true;} else {return false;}` :) – vp_arth Nov 22 '14 at 12:44

3 Answers3

1

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.

Lauri Elias
  • 1,231
  • 1
  • 21
  • 25
1

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 (===).

Oskar Lindberg
  • 2,255
  • 2
  • 16
  • 36
  • What I meant to ask is if the two were interchangeable. I now understand that my statement could possibly return undefined rather than false. – user3697034 Nov 22 '14 at 12:44
0

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

Santosh Panda
  • 7,235
  • 8
  • 43
  • 56