JavaScript – Testing For Negative Zero

One thing that I always took for granted until last week was testing for negative numbers. What I mean is that I had no clue that -0 is actually different from 0. Interestingly enough when using strict equality to test the two values they still appear to be equal but they are in fact different. For this reason, I decided to write the following function:

function isNegative(n) {
  return ((n = +n) || 1 / n) < 0;
}

I admit that this function probably isn't that useful because I haven't thought of one time when you really need to know if a value is -0 or 0, but just in case I or anyone else in the future does need a way to differentiate, the above function should do the trick. The following are some examples of calling the function:

var a = isNegative(-Infinity); // true
var b = isNegative(-12);       // true
var c = isNegative(-0);        // true
var d = isNegative(0);         // false
var e = isNegative(34);        // false
var f = isNegative(Infinity);  // false
var g = isNegative("Hello");   // NaN -> false
var h = isNegative(undefined); // NaN -> false
var i = isNegative(null);      // 0 -> false
var j = isNegative(-null);     // -0 -> true
var k = isNegative("-5");      // -5 -> true
var l = isNegative("-0");      // -0 -> true
var m = isNegative("0");      // 0 -> false
var n = isNegative("6");      // 6 -> false
var o = isNegative("");      // 0 -> false

I'm guessing this is more than you ever wanted to know about negative numbers so I will end the post here. 😎

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! 😎

EcmaScript 6 – Array.of()

A function that is proposed to be added to EcmaScript 6 is Array.of(). This function will be used to create an array of the passed parameters. Since this function is available in some browsers but not in all, here is a block of code which when executed will define it if not already defined:

Array.of = Array.of || function() {
  return Array.prototype.slice.call(arguments);
};

Here are some examples of using the function:

var a = Array.of(1,2,3);     // [1,2,3]
var b = Array.of();          // []
var c = Array.of(undefined); // [undefined]
var d = Array.of(null);      // [null]
var e = Array.of(4);         // [4]

Not the most amusing function, but it is still a step towards EcmaScript 6. 😎