This rule triggers when legacy mathematical expressions are used that can be replaced with modern Math APIs introduced in ES2015.
ES2015 introduced many new Math methods that provide clearer, more readable alternatives to complex mathematical expressions. Using these modern APIs offers several benefits:
Improved readability: Modern Math methods express mathematical intent more clearly. For example, Math.log10(x)
immediately tells you that you’re calculating a base-10 logarithm, while Math.log(x) / Math.LN10 requires mathematical knowledge to
understand.
Better performance: Native Math methods are typically optimized by JavaScript engines and can perform better than equivalent manual calculations.
Reduced error potential: Complex mathematical expressions are more prone to mistakes. Using dedicated methods reduces the chance of calculation errors.
Standardized approach: Modern Math APIs provide a consistent way to perform common mathematical operations across different codebases.
The most common cases involve logarithmic calculations and distance calculations using the Pythagorean theorem, where the intent becomes much clearer with modern APIs.
Using legacy mathematical patterns instead of modern Math APIs reduces code readability and maintainability. Complex expressions are harder to understand and more error-prone. Performance may also be suboptimal compared to native implementations.
Replace Math.log() expressions with Math.log10() for base-10 logarithms.
const result1 = Math.log(x) * Math.LOG10E; // Noncompliant const result2 = Math.log(x) / Math.LN10; // Noncompliant
const result1 = Math.log10(x); const result2 = Math.log10(x);