EcmaScript 6 – Math.sign()

One function I didn’t think would be doable in most browsers was the Math.sign. My main worry was that on the MDN page it specifies a difference between negative zero and positive zero. After doing some research I found this page which helped me realize there is a way to determine if you are dealing with normal zero or negative zero. With that in mind, my proposed definition for Math.sign is as follows:

Math.sign = Math.sign || function(n) {
  return (n = +n) ? n < 0 ? -1 : 1 : n;
};

As far as I can tell, this JavaScript function definition is a good equivalent to make the function available on browsers that dont yet natively provide this feature. Have fun! šŸ˜Ž

Leave a Reply

Your email address will not be published. Required fields are marked *