Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Subtracting Zero some sort of JavaScript performance trick?

Looking in the jQuery core I found the following code convention:

nth: function(elem, i, match){
    return match[3] - 0 === i;
},

And I was really curious about the snippet match[3] - 0

Hunting around for '-0' on google isn't too productive, and a search for 'minus zero' brings back a reference to a Bob Dylan song.

So, can anyone tell me. Is this some sort of performance trick, or is there a reason for doing this rather than a parseInt or parseFloat?

like image 723
James Wiseman Avatar asked Apr 19 '10 08:04

James Wiseman


1 Answers

Probably just a short-hand way to force the left-hand side into integer. Not as clear as calling a function, of course.

This tutorial on type-conversion states:

Any mathematical operator except the concatenation/addition operator will force type-conversion. So conversion of a string to a number might entail performing a mathematical operation on the string representation of the number that would not affect the resulting number, such as subtracting zero or multiplying by one.

This also reveals that "subtracting" is a better search term than "minus". :)

like image 188
unwind Avatar answered Oct 19 '22 23:10

unwind