Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you use 0 > 0 in javascript?

Tags:

javascript

I was going through some of StackOverflow's client side code and I ran across this block of JavaScript in the source-code of https://stackoverflow.com/questions/ask:

if ($answerCheckbox.is(':checked') || 0 > 0) {
     $answerCheckbox.attr('checked', true);
     $('#question-only-section').hide();
     StackExchange.using("editor", function () {
          setTimeout(function () { showAnswerSection(true) }, 2);
     });
}

Why wouldn't you use false instead?

like image 310
John Avatar asked Sep 12 '12 19:09

John


People also ask

What does 0 do in JS?

0 is an argument passed to void that does nothing, and returns nothing. JavaScript code (as seen above) can also be passed as arguments to the void method. This makes the link element run some code but it maintains the same page.

Why is 0 not a number in JavaScript?

In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.

What happens if you divide by 0 in JavaScript?

The output of the code in JavaScript is as follows: Dividing the number 0 by 0 returns NaN. Dividing the positive number by 0 returns Infinity. Dividing the negative number by 0 returns -Infinity.


4 Answers

You're assuming the code is all natively written Javascript. It isn't uncommon to see some server-generated script which references elements via some programmatic identifier which resolves like this at runtime, which admittedly looks a little peculiar.

like image 195
David W Avatar answered Sep 28 '22 11:09

David W


It is generated code (not in a .js) file so obviously one of those two values is not always 0 but a server-side variable.

like image 25
ThiefMaster Avatar answered Sep 28 '22 11:09

ThiefMaster


There is no reason for it... but until you know the server side code, you can't know for sure.

Let's say (PHP) you had a variable $x=1 and could also be $x=0 depending on the scenario.

if ($answerCheckbox.is(':checked') || <?php echo $x;?> > 0) {

That code makes perfect sense....

like image 43
Tim Withers Avatar answered Sep 28 '22 09:09

Tim Withers


Because that line probably comes from php, like so:

if ($answerCheckbox.is(':checked') || <?php echo $tot; ?> > 0) {

I know because in some situations I had to write code like that.

like image 28
Nelson Avatar answered Sep 28 '22 11:09

Nelson