-4

Considering text as an array variable, please explain the push method statement shown below:

var text = [];
text.push(document.getElementById('name').innerHTML || 0);
j08691
  • 204,283
  • 31
  • 260
  • 272
user1934643
  • 165
  • 1
  • 10

2 Answers2

1

The trick is that an empty string is evaluated as false in boolean tests like this.

Example :

var a = "" || 0;          // a is set to 0 because "" is empty and is false
var b = "non-empty" || 0  // b is set to "non-empty" because it's not an empty string
Mike Park
  • 10,845
  • 2
  • 34
  • 50
  • Thank so much climbage, though I was also guessing the same but was doubtful so wanted to get it confirmed with experts as I have never seen such an expression before....Once again a big thanks to you for making me clear on this :-) – user1934643 Jan 18 '13 at 20:02
  • Technically, `""` is falsy, not false – John Dvorak Jan 18 '13 at 20:04
  • @user1934643 Okay, I kinda regret my close vote now (too late, I know). Just FYI, this kind of use of `||` is called "short-circuit boolean evaluation". See the question linked as possible duplicate in the comments above. – bfavaretto Jan 18 '13 at 20:05
  • @bfavaretto it's never too late to retract a close vote. We have a thing called "reopen votes". However, if this gets reopened, the next step will be to close this as a duplicate. – John Dvorak Jan 18 '13 at 20:06
  • @JanDvorak In this particular case, I regret the close vote *reason* (I'd prefer "dupe", but couldn't find a good one and voted for "too localized"). So I won't vote to reopen just to have it closed again. – bfavaretto Jan 18 '13 at 20:08
0

it will add HTML content of dom element with id='name' if it's not empty to text array , otherwise it will add 0 to it

Basemm
  • 1,204
  • 14
  • 16