DEV Community

Barret Blake
Barret Blake

Posted on • Originally published at barretblake.dev on

Function Friday – More Math

I previously covered some of the base math functions available. This time I’ll cover the math functions that are related to working with arrays of numbers. This includes the max, min, rand, and range functions.

max & min

These two functions work the exact same way. The max function returns the largest number in an array of numbers, and the min function returns the smallest number in an array of numbers. The format is as follows:

max(number1, number2, number3, ....)
max([number1, number2, number3, ....])
min(number1, number2, number3, ....)
min([number1, number2, number3, ....])
Enter fullscreen mode Exit fullscreen mode

The numbers can be of any type (integer, float or a mixture) and the [] brackets are optional if you’re passing in a literal array. You can also pass in a single array variable. The result will be a single number which is either the largest or smallest number respectively.

For example:

max(2.1, 4, 6.4, 8) //returns 8
min(2.1, 4, 6.4, 8) //returns 2.1
Enter fullscreen mode Exit fullscreen mode

Range

The range function will allow you to generate an array of integers. The format is as follows:

range(startingNumber, numberCount)
Enter fullscreen mode Exit fullscreen mode

The startingNumber is the number at which you want to start the array. And the numberCount is the number of items to add to the array. Each number added will be one higher than the last. Only integer numbers are supported, and not float numbers.

For example:

range(5,5) //will return [5,6,7,8,9]
range(11,7) //will return [11,12,13,14,15,16,17]
Enter fullscreen mode Exit fullscreen mode

rand

The rand function will return a random integer number between two provided numbers, inclusive of the starting number and exclusive of the ending number. The format is as follows:

rand(startingValue, endingValue)
Enter fullscreen mode Exit fullscreen mode

Only integer numbers are supported and not float numbers.

Example:

rand(1,5) //will return 1, 2, 3, or 4
rand(21,28) //will return 21, 22, 23, 24, 25, 26, or 27
Enter fullscreen mode Exit fullscreen mode

The post Function Friday – More Math first appeared on Barret Codes.

Top comments (0)