Get the absolute value and sign of a number in JavaScript
Beginner · 3 min read
Every number has two parts: its size and its direction. -7 has a size of 7 and points below zero. JavaScript gives you one function for each part. Math.abs keeps the size and drops the sign, and Math.sign keeps only the direction. Together they answer everyday questions like "how far apart are these two balances?" or "is this account in credit or overdrawn?".
In this tutorial you will use both, then write distance(a, b), the gap between two numbers whichever way round you pass them. You will also see how these functions treat text, which isn't what most people expect. You need to know what a number and a function are.
Size: absolute value
The absolute value is how far a number is from zero, ignoring direction. Both 7 and -7 are 7 steps from zero:
console.log(Math.abs(-7)); // 7
console.log(Math.abs(7)); // 7
console.log(Math.abs(0)); // 0
Direction: sign
Math.sign reduces a number to one of three answers: -1 for negative, 0 for zero and 1 for positive. The size doesn't matter:
console.log(Math.sign(-3)); // -1
console.log(Math.sign(0)); // 0
console.log(Math.sign(1200)); // 1
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
53 Absolute value and sign
easyGet the size of a number regardless of direction, and separately get its direction. Use them together to find the distance between two account balances.
Stuck? Three hints, smallest first
- 1.
Math.absdrops the sign;Math.signkeeps only the sign. - 2.
Math.signanswers-1,0or1— and for-0it answers-0. - 3. The distance between two numbers is
Math.abs(a - b), whichever way round they are.
Step 1: store money as whole numbers
The answer works with two account balances in naira. Money is stored in kobo, the smallest unit (100 kobo make 1 naira), so every amount is a whole number and the sums are exact. JavaScript lets you put underscores inside a number to make it easier to read. They don't change the value:
const balanceA = -450_00; // overdrawn by 450 naira
const balanceB = 1_200_00; // 1,200 naira in credit
console.log(balanceA); // -45000
console.log(balanceB); // 120000
Writing 450_00 reads as "450 naira and 00 kobo" while staying one number.
Step 2: the gap between two balances
Subtracting gives the gap, but the sign depends on which balance comes first:
console.log(-450_00 - 1_200_00); // -165000
console.log(1_200_00 - -450_00); // 165000
A gap is a size, so it shouldn't be negative. Wrap the subtraction in Math.abs:
const distance = (a, b) => Math.abs(a - b);
const balanceA = -450_00;
const balanceB = 1_200_00;
console.log(distance(balanceA, balanceB)); // 165000
console.log(distance(balanceB, balanceA)); // 165000
Same answer either way round: 165,000 kobo, which is 1,650 naira.
Step 3: use the sign to describe a balance
Math.sign is handy when you want to pick a label based on direction:
const label = (kobo) => ['overdrawn', 'empty', 'in credit'][Math.sign(kobo) + 1];
console.log(label(-450_00)); // overdrawn
console.log(label(0)); // empty
console.log(label(1_200_00)); // in credit
Adding 1 turns -1, 0 and 1 into 0, 1 and 2, which are positions in the list of labels.
Step 4: what happens with text
Math.abs doesn't refuse text. It quietly converts it to a number first:
console.log(Math.abs('-7')); // 7
console.log(Math.abs('lagos')); // NaN
'-7' converts to -7, so you get 7. 'lagos' can't be converted, so you get NaN, "Not a Number". NaN doesn't throw an error. It spreads through every sum it touches, so a single bad value can turn a whole total into NaN.
To check for it, use Number.isNaN. A plain === NaN never works, because NaN is not equal to anything, not even itself:
console.log(Number.isNaN(Math.abs('lagos'))); // true
console.log(NaN === NaN); // false
Step 5: minus zero
JavaScript has a zero with a minus sign, -0. It counts as equal to 0 with ===, but Math.sign keeps its sign. Object.is is the comparison that can tell them apart:
console.log(Object.is(Math.sign(-0), -0)); // true
console.log(-0 === 0); // true
You will rarely meet -0, but if you ever sort or group by Math.sign, a "zero" row can show up on the negative side because of it.
The full solution
The answer panel has distance and the two balances, and prints abs and sign for a few values, the gap in kobo, and what happens with text. The checks confirm the distance works both ways round and cover minus zero and NaN. Press Run to see the output.
const distance = (a, b) => Math.abs(a - b);
// Money in kobo, so the arithmetic is exact.
const balanceA = -450_00; // overdrawn by 450 naira
const balanceB = 1_200_00;
console.log('abs(-7) ->', Math.abs(-7));
console.log('sign(-3) ->', Math.sign(-3), 'sign(3) ->', Math.sign(3), 'sign(0) ->', Math.sign(0));
console.log('gap in kobo ->', distance(balanceA, balanceB));
console.log('abs of text ->', Math.abs('-7'), '<- coerced, quietly');
console.log('abs of rubbish ->', Math.abs('lagos'));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('size without direction', Math.abs(-7), 7);
test('a positive is untouched', Math.abs(7), 7);
test('the distance is the same either way round', distance(balanceA, balanceB) === distance(balanceB, balanceA), true);
test('and it is 1650 naira', distance(balanceA, balanceB), 165000);
test('sign reduces to three answers', [Math.sign(-3), Math.sign(0), Math.sign(3)], [-1, 0, 1]);
test('but minus zero keeps its sign', Object.is(Math.sign(-0), -0), true);
test('text is coerced rather than refused', Math.abs('-7'), 7);
test('and nonsense gives NaN', Number.isNaN(Math.abs('lagos')), true);
Math.abs coerces before it computes, so Math.abs('-7') is 7 and Math.abs('lagos') is NaN. That NaN then spreads through every sum it touches without throwing, which is why the check is Number.isNaN(...) against true and not test('...', x, NaN) — the latter would pass even if x were the wrong value entirely, since JSON.stringify(NaN) is "null".
Math.sign(-0) being -0 is a curiosity until you sort by it, at which point a "zero" row lands on the negative side. Note the 450_00 digit separator: it reads as naira-and-kobo while staying one integer.
Common mistakes
- Subtracting without
Math.abs. The gap comes out negative when the arguments are the other way round. - Checking
x === NaN. It is always false. UseNumber.isNaN(x). - Expecting
Math.absto reject text. It converts first, so'-7'works and'lagos'givesNaNwithout an error.
Try it yourself
- Write
isCloseTo(a, b, allowed)that returnstruewhen the gap betweenaandbis at mostallowed. - Turn a list of daily temperature changes,
[-3, 2, -1, 4], into their sizes, then add them up. - Format a balance in kobo as text, like
-₦450.00or₦1,200.00, usingMath.signfor the minus andMath.absfor the amount.