JavaScript Math
Basic Math Operators
3 + 2 // Addition
3 - 2 // Subtraction
3 * 2 // Multiplication
3 / 2 // Division
3 % 2 // Modulus (remainder after division)
Math.sqrt(4) // Square root
Math.pow(4,3) // Exponent (e.g. 4 to the power of 3)
- Spaces between numbers and math symbols are optional
Rounding:
Math.round(3.123) // Rounds to the nearest whole number (e.g. 3)
Math.floor(3.123) // Rounds down (e.g. 3)
Math.ceil(3.123) // Rounds up (e.g. 4)
Trigonometry:
Math.PI // Pi: 3.14159...
Math.sin(Math.PI/4) // Calculates the sine of an angle in radians (e.g. 0.707)
Math.cos(Math.PI/4) // Cosine
Math.tan(Math.PI/4) // Tangent
Math.asin(1/2) // Calculates the arc sine, giving the angle in radians (e.g. 0.524)
Math.acos(1/2) // Arc cosine
Math.atan(1/2) // Arc tangent
Math.hypot(1,2) // Calculates hypotenuse length, given length of other legs of right triangle
- It's easiest to work with radians consistently in the code, then convert it to degrees right before displaying it to the user if needed
Logarithms:
Math.E // Euler's number, e: 2.718...
Math.log(Math.E) // Natural log (e.g. 1)
Math.log10(100) // Log base 10 (e.g. 2)
Other:
Math.max(209,123) // Gets the greatest of two numbers (e.g. 209)
Math.min(209,123) // Gets the least of two numbers (e.g. 123)
Math.random() // Generates a random number between 0 and 1, including 0
- To generate a random number between 0 and some number x, multiply the random number by x + 1, then round down
Challenge
Write code that will display the square root of the fraction of 11 divided by pi, but don't use any number besides 1 in the code.
Completed