In JavaScript, a Math object does not need to be created; it exists as a compact mathematical browser coprocessor. Math is always available anywhere in JavaScript code. It includes basic constants in the form of properties and popular mathematical functions in the form of methods.
JavaScript Math is a traditional math, daily essential, accessible and easy to use.
Math Properties
Basic mathematical constants:
- base of the natural logarithm (E);
- natural logarithm (LN2, LN10);
- logarithm of a number (LOG2E, LOG10E);
- Pi number (PI);
- square roots (SQRT1_2, SQRT2).
To access a property of a global JavaScript Math object, specify the name of the object and the name of the required property. For instance,
- var exp = Math.E; // constant e ~ 2.718
- var n314 = Math.PI; // Pi number ~ 3.1415
Usually, variables do not describe in advance, but use the properties of the JavaScript Math object directly in the expression. However, the algorithm may require its own approach. Mathematical constants in the form of properties of the Match object work in any syntax constructs of the JavaScript language.
Positive number and string
If you want to get the absolute value of a number, use 'abs' - a function that makes any number positive.
- Math.abs ('- 65'); // = 65
- Math.abs (19); // = 19
- Math.abs (0); // = 0
To convert a number to a character string for a specific reason, the toString (rdx) function is applied directly to the variable. For instance,
- var iPos = (a / b) .toString (10);
- var iPos = (a / b) .toString (2);
- var iPos = (a / b) .toString (8);
- var iPos = (a / b) .toString (16).
Here the parameter 'rdx' is the base of the number system, respectively, decimal, binary, octal and hexadecimal. Instead of the expression '(a / b)', you can specify the variable name.
Base-to-number conversion is a very useful feature. When you need to generate a color code (write down the required sequence of hexadecimal digits) programmatically, it is simply irreplaceable.
Many CSS rules or styles of specific elements have to be formed on the fly or while the site is working. Using the JavaScript Math object can be found even on the simplest site.
Important. Expression:
- var iPos = Math.abs ('- 1,3');
will not work as it should.
The result will be 'NaN'. The separation of the integer and fractional parts in JavaScript is indicated by a period, not a comma. But the expression:
- var iPos = ('100,33'). toString ();
will give the result: '100.33'. In this case, it is written in the style of JavaScript Math, but the result is formed as a string into a string.
In JavaScript code, it is often not a specific flaw in the algorithm by the developer that leads to serious errors, but inappropriate consideration of the language’s features to cut off everything that is not provided or does not fit into the syntax .
Rounding Functions
The ability of the JavaScript Math object to round values and results of evaluating expressions is very important. They are not as widely represented here as in other languages, but their functionality is quite enough for almost any task.
It's common knowledge that CSS style rules, DOM object properties, and other elements require integer arguments. In some cases, values with a fractional part of one or more digits are required. In addition to the usual (mathematical) rounding - the Math.round function, JavaScript offers two more options: up (ceil) and down (floor).
As a rule, numerical data should be integer or have a specific number of digits after the decimal point. When it is necessary to adjust the position of the decimal point in a number, it is convenient to use the classical idea of dividing (multiplying) the desired number by dividing by 10, 100, 1000 ...
- var x = Math.round (20.5); // = 21
- var x = Math.ceil (1.1); // = 2
- var x = Math.floor (1.1); // = 1
- var x = Math.floor (1.11 * 10); // = 11
In the last example, the capabilities of the math floor javascript function are used by the code somewhat incorrectly. Although much depends on the logic of a particular task. Adjusting the position of the decimal point by multiplying or dividing by 10, 100, 1000, ... is most convenient after rounding, and not in front of it.
Important. When using numbers as arguments, often errors arise precisely because the result of a calculation, for example, the coordinates or sizes of blocks, has a real or lowercase value that cannot be converted to a number.
Math functions
In addition to trigonometric functions: calculating sine (sin), cosine (cos) and tangent (tan), the Math object offers arcsine (asin), arcosine (acos) and arctangent (atan).
You can also calculate the exponent (exp) - "e" in a power, calculate the natural logarithm of a number (log), extract the square root of a number (sqrt), and raise the number to the desired power (pow).
The use of mathematical functions is similar to round, floor, and ceil, with the exception of the pow function, which has two arguments: the first is a number, the second is the degree to which it needs to be raised.
Trigonometric functions are a good part of the JavaScript Math, of course, but you should not get carried away. JavaScript is not a mathematical machine, but a browser language whose concern is to serve pages, DOM objects, and do a lot of routine work.
The purpose of the object is to provide sufficient mathematical apparatus for performing specific work, and not for calculating integrals, flying to the moon and creating unique animations. Many math sites run very slowly.
Minimum, maximum and random values
The implementation of the min and max functions involves a different number of compared numbers.
Both functions accept a number of arguments: not only two arguments are required. The result of min will be the minimum of the numbers passed to the function, the result of max will be the maximum.
If at least one argument is undefined, the result will be 'NaN'.
The random function generates a pseudo-random number from 0 to 1. Its application is incredibly wide.
The padl () function is used here, which padding the number with zero if it has one digit. Calling viuq () will produce a relatively random number, but unique enough not to repeat for one day.
If you need more uniqueness, you can call the function twice and combine the obtained values or calculate the number taking into account seconds.
Giving any element of the page, file name or image, session of the visitor, control security using the random function is very fast and convenient.