Find the distance between two numbers in JavaScript
Beginner · 4 min read
How far apart are 3 and 10? You know straight away: 7. And 10 and 3? Still 7. Distance doesn't care which number comes first. Apps ask this question all the time: how far a temperature moved, how many points separate two teams, how many days lie between two dates.
In this tutorial you will write a function called gap(a, b) that gives the distance between two numbers, in either order. On the way you will meet Math.abs, one of the most useful functions in JavaScript's Math toolbox. You only need to know how to write a small function.
What "absolute value" means
The absolute value of a number is its size with the sign removed. The absolute value of -5 is 5, and the absolute value of 5 is also 5. Think of it as "how far from zero", ignoring which side of zero you are on.
JavaScript gives you this as Math.abs:
console.log(Math.abs(-5)); // 5
console.log(Math.abs(5)); // 5
console.log(Math.abs(0)); // 0
Math.abs never returns a negative number. That single fact is what makes it right for distances.
Here is the exercise. Have a go yourself if you like, or read on and we will build it step by step.
2 Absolute value and the gap between two numbers
easyReturn the magnitude of a number regardless of sign, then use it to write gap(a, b) giving the distance between two numbers in either order.
Stuck? Three hints, smallest first
- 1.
Math.absstrips the sign and never returns a negative. - 2. The distance between two numbers is the absolute value of their difference.
- 3.
Math.abscoerces its argument first, so a numeric string works and a word givesNaN.
Step 1: subtract the two numbers
The distance between two numbers starts with subtracting one from the other. A first try:
const gap = (a, b) => a - b;
console.log(gap(10, 3)); // 7
console.log(gap(3, 10)); // -7
The first call is right. The second gives -7, and a distance can't be negative. The answer depends on which number the caller passed first, which is exactly what we want to avoid.
Step 2: the "if" fix, and why to skip it
One way out is to always subtract the smaller number from the bigger one:
const gapWithBranch = (a, b) => (a > b ? a - b : b - a);
console.log(gapWithBranch(3, 10)); // 7
It works. But it has two branches, and it is easy to swap them by mistake (a - b where you meant b - a). There is a shorter way with nothing to get backwards.
Step 3: wrap the difference in Math.abs
a - b and b - a always have the same size and opposite signs. Removing the sign gives the same answer both ways round:
const gap = (a, b) => Math.abs(a - b);
console.log(gap(3, 10)); // 7
console.log(gap(10, 3)); // 7
console.log(gap(-4, 6)); // 10
The last line crosses zero: from -4 up to 0 is 4, and from 0 up to 6 is 6, so 10 in total. Math.abs handles that without any special case. This one line is the whole function.
Step 4: what Math.abs does with text
Math.abs first turns its argument into a number. This is called coercion: JavaScript converting a value from one type to another for you.
console.log(Math.abs('-3')); // 3
console.log(Math.abs('twenty')); // NaN
A numeric string like '-3' becomes the number -3, so you get 3. A word like 'twenty' can't become a number, so you get NaN, which stands for "Not a Number". NaN doesn't throw an error. It quietly spreads through every sum it touches:
console.log(Math.abs('twenty') + 10); // NaN
If a value comes from a form field or another program, check it with Number.isFinite before doing math on it:
console.log(Number.isFinite(Math.abs('twenty'))); // false
Step 5: a few edge cases
Two more inputs are worth knowing about:
console.log(Math.abs(-Infinity)); // Infinity
console.log(Object.is(Math.abs(-0), 0)); // true
JavaScript has a "minus zero", written -0. Math.abs(-0) gives an ordinary 0. Object.is is a strict comparison that can tell the two zeros apart, so it confirms the result really is plain zero. You will meet -0 properly in the next exercise.
The full solution
The answer panel has the one-line gap function and prints Math.abs on positives, negatives, strings and -0. The checks underneath confirm each result, including that Math.abs never returns a negative. Press Run to see it all.
const gap = (a, b) => Math.abs(a - b);
console.log('abs(-5) :', Math.abs(-5));
console.log('abs(5) :', Math.abs(5));
console.log('gap(3, 10) :', gap(3, 10), 'and the other way round:', gap(10, 3));
console.log("abs('-3') :", Math.abs('-3'), '<- coerced to a number first');
console.log("abs('twenty'):", Math.abs('twenty'));
console.log('abs(-0) :', Math.abs(-0), 'is it exactly +0?', Object.is(Math.abs(-0), 0));
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('abs of a negative drops the sign', Math.abs(-5), 5);
test('abs of a positive changes nothing', Math.abs(5), 5);
test('the gap is the same in either direction', [gap(3, 10), gap(10, 3)], [7, 7]);
test('a gap across zero adds up', gap(-4, 6), 10);
test('abs coerces a numeric string', Math.abs('-3'), 3);
test('and gives NaN for something unparseable', Number.isNaN(Math.abs('twenty')), true);
test('abs of -0 is exactly +0', Object.is(Math.abs(-0), 0), true);
test('abs of -Infinity is Infinity', Math.abs(-Infinity) === Infinity, true);
test('and abs never returns anything negative', [-3, 0, 9, -0].every((n) => Math.abs(n) >= 0), true);
gap is the shape to remember: Math.abs(a - b) is symmetric, so callers cannot get the argument order wrong. Writing a > b ? a - b : b - a does the same job with a branch that can be inverted by mistake.
Math.abs coerces, which is convenient and occasionally hides a bug: a form field holding "twenty" silently becomes NaN, and NaN then poisons every later sum without throwing. If the input came from outside your code, check it with Number.isFinite before doing arithmetic on it.
Common mistakes
- Returning
a - bon its own. It's correct only whenais the bigger number. Wrap it inMath.absso the order stops mattering. - Taking the absolute value of each number first.
Math.abs(a) - Math.abs(b)is not a distance. For -4 and 6 it gives-2instead of10. - Trusting input from outside.
Math.abs('twenty')isNaN, not an error. Check withNumber.isFinitefirst.
Try it yourself
- Write
isClose(a, b)that returnstruewhen two numbers are less than 0.5 apart. Use yourgap. - Given a list of temperatures,
[21, 25, 19, 30], find the biggest jump between two neighboring days. - Predict what
gap('8', 3)returns, then run it. Why does it work even though'8'is text?