0

I found some piece of code which contains following loop:

for (var i = 0; i < 3; i++) {
  tabMap['tab' + i] = { element : null };

  i && (tabMap['tab' + i].left = 'tab' + (i - 1)); //??
  i < 2 && (tabMap['tab' + i].right = 'tab' + (i + 1)); //??
}

What do the selected lines mean (the ones with commented question marks)?

sunpietro
  • 2,059
  • 4
  • 24
  • 42

2 Answers2

2

That is the same as the following:

for (var i = 0; i < 3; i++) {
  tabMap['tab' + i] = { element : null };

  if ( i ) {
      tabMap['tab' + i].left = 'tab' + (i - 1); //??
  }
  if ( i < 2 ) {
      tabMap['tab' + i].right = 'tab' + (i + 1); //??
  }
}

The && means that if it's true, check the next statement, which is why it is put in parentheses. It's merely a shortcut for the above.

kalley
  • 18,072
  • 2
  • 39
  • 36
  • Thank you very much for explanation. What about: `i || (tabMap['tab' + i].left = 'tab' + (i - 1));` I found something like this somewhere in the code. – sunpietro Jul 06 '13 at 16:52
  • It's like `if ( ! i ) { tabMap['tab' + i].left = 'tab' + (i - 1); }`. `&&` will continue down the chain of statements, but `||` will stop when it hits something that is truthy. – kalley Jul 06 '13 at 16:55
2

You have to understand that expressions that are connected with a logical AND (&&) only evalute until the first expression evaluates to false (or is falsy). So, the following piece of code means:

  1. evaluate expr1
  2. if (expr1): evaluate expr2

    expr1 && expr2;
    

In your case expr1 is the index i, which means, that your code translates to something like this:

if (i) {
    tabMap['tab' + i].left = 'tab' + (i - 1);
}

This if condition will evalute to true if i is greater then zero. So, what the if condition should look like is:

if (i > 0) {
    tabMap['tab' + i].left = 'tab' + (i - 1);
}

The same goes for your second statement.

I personally find not good practice at all to hide the meaning of your code by doing clever things like expr1 && expr2. If you want to do something if the index is greater then zero, then you should write it that way. I know you didn't write the code but I just had the urge to say that.

basilikum
  • 10,378
  • 5
  • 45
  • 58