Welcome to our deep dive into ES6 Math Methods! In this tutorial, we'll explore various mathematical functions introduced in ES6, providing practical examples to help you understand them better.
By the end of this tutorial, you'll have a solid understanding of these methods and be able to apply them in your own projects. Let's get started!
ES6, or ECMAScript 6, introduced several new features to JavaScript, including math methods. These functions make it easier to work with numbers and perform mathematical operations in your code.
Here are some basic math methods in ES6:
Math.abs(num): Returns the absolute value of a number.Math.ceil(num): Rounds a number up to the nearest integer.Math.floor(num): Rounds a number down to the nearest integer.Math.round(num): Rounds a number to the nearest integer. If the middle digit is 5 or greater, it rounds up; otherwise, it rounds down.Math.max(num1, num2, ...): Returns the largest number from a list of numbers.Math.min(num1, num2, ...): Returns the smallest number from a list of numbers.// Absolute value
console.log(Math.abs(-5)); // Output: 5
// Ceiling
console.log(Math.ceil(2.1)); // Output: 3
// Floor
console.log(Math.floor(2.9)); // Output: 2
// Rounding
console.log(Math.round(2.5)); // Output: 2
console.log(Math.round(2.6)); // Output: 3
// Max
console.log(Math.max(1, 5, 3, 4)); // Output: 5
// Min
console.log(Math.min(1, 5, 3, 4)); // Output: 1ES6 also offers trigonometry functions:
Math.sin(num): Returns the sine of a number in radians.Math.cos(num): Returns the cosine of a number in radians.Math.tan(num): Returns the tangent of a number in radians.Math.asin(num): Returns the arc sine of a number between -1 and 1.Math.acos(num): Returns the arc cosine of a number between 0 and π.Math.atan(num): Returns the arc tangent of a number in radians.// Sin
console.log(Math.sin(Math.PI / 4)); // Output: 0.7071067811865475
// Cos
console.log(Math.cos(Math.PI / 4)); // Output: 0.7071067811865476
// Tan
console.log(Math.tan(Math.PI / 4)); // Output: 1
// Arc Sine
console.log(Math.asin(0.5)); // Output: 0.5235987755982989
// Arc Cosine
console.log(Math.acos(0.5)); // Output: 1.5707963267948966
// Arc Tangent
console.log(Math.atan(1)); // Output: 0.7853981633974483ES6 offers functions for solving quadratic equations:
Math.sqrt(num): Returns the square root of a number.Math.pow(num1, num2): Raises a number to a power.// Square root
console.log(Math.sqrt(16)); // Output: 4
// Power
console.log(Math.pow(2, 3)); // Output: 8Which function returns the square root of a number?
In this tutorial, we covered various ES6 math methods, providing practical examples to help you understand their usage. Now that you've learned about these functions, you can use them to simplify mathematical operations in your JavaScript projects.
Keep practicing and expanding your knowledge by exploring other ES6 features. Happy coding! 🎉