Math.abs(x)
There are some math calculations that require you to find the absolute value of a value, ignoring the negative sign. Math.abs(x) does not change the value of x, rather it returns the absolute value of x.
Examples
Example: Typical Usage
var y = Math.abs(-23);
console.log(y);
Example: Distance between two points
Use coordinates to calculate the horizontal and vertical distance between two points. This example also uses Math.round to display results
// Use coordinates to calculate the horizontal and vertical distance between two points. This example also uses Math.round to display results.
var x1 = getX();
var y1 = getX();
arcRight(123, 60);
var x2 = getX();
var y2 = getY();
var horizontalDistance = Math.abs(x2-x1);
var verticalDistance = Math.abs(y2-y1);
console.log("The turtle traveled " + Math.round(horizontalDistance) + " pixels horizontally.");
console.log("The turtle traveled " + Math.round(verticalDistance) + " pixels vertically");
Example: Increments of distance
Move the turtle a number of times at random, and keep track of the total distance traveled.
// Move the turtle a number of times at random, and keep track of the total distance traveled.
var distance = 0;
for (var i = 0; i < 4; i++) {
var y = randomNumber(-100, 100);
console.log("Move " + y + " units.");
moveForward(y);
distance = distance + Math.abs(y);
}
console.log("The turtle has moved a total of " + distance + " units.");
Syntax
Math.abs(x);
Parameters
Name | Type | Required? | Description |
---|---|---|---|
x | number | An arbitrary number, variable, or expression that results in a number. |
Returns
Found a bug in the documentation? Let us know at support@code.org.