Math.sign and Math.abs Keep Negatives Honest

Classify and normalize numbers with Math.sign and Math.abs: sign preserves -0 as -0, abs collapses it to 0, and both propagate NaN untouched.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
const values = [5, -3, 0, -0, NaN, Infinity, -Infinity];

for (const v of values) {
  console.log(v, "sign:", Math.sign(v), "abs:", Math.abs(v));
}

// Math.sign 区分 -0 与 0:-0 返回 -0,0 返回 0
console.log("sign(-0):", Math.sign(-0) === -0);

// Math.abs 对 -0 返回 0:消除负零
console.log("abs(-0):", Math.abs(-0) === 0);

// Math.abs 对 NaN 仍是 NaN,不会变 0
console.log("abs(NaN):", Number.isNaN(Math.abs(NaN)));

// 经典用途:取绝对差值
function delta(a, b) {
  return Math.abs(a - b);
}
console.log("delta:", delta(10, 3), delta(-5, 5));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

5 sign: 1 abs: 5
-3 sign: -1 abs: 3
0 sign: 0 abs: 0
-0 sign: -0 abs: 0
NaN sign: NaN abs: NaN
Infinity sign: 1 abs: Infinity
-Infinity sign: -1 abs: Infinity
sign(-0): true
abs(-0): true
abs(NaN): true
delta: 7 10

Inside the snippet

Math.sign and Math.abs Keep Negatives Honest comes down to the function delta.

A single loop drives the file — for (const v of values).

Caveats

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.

Using it

The one function declared in the file is function delta(a, b)

Expect labeled output — sign(-0):, abs(-0):, abs(NaN): — when the file runs.

Key statements

return Math.abs(a - b);

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. The file defines `delta` at load time.