Skip to content

math/prefer-math-sqrt

enforce the use of Math.sqrt() instead of other square root calculations

  • ⚙️ This rule is included in "plugin:math/recommended".
  • 🔧 The --fix option on the command line can automatically fix some of the problems reported by this rule.
  • 💡 Some problems reported by this rule are manually fixable by editor suggestions.

📖 Rule Details

This rule aims to enforce the use of Math.sqrt() instead of other square root calculations.

Using Math.sqrt() provides several advantages:

  • Clarity of intent: Immediately obvious that you're calculating a square root
  • Performance: Optimized native implementation
  • Reliability: Handles edge cases consistently
  • Standard practice: Widely recognized mathematical function
Now loading...

Important Edge Case

Note that the results are different when the input is -Infinity:

js
Math.sqrt(-Infinity)        // NaN
Math.pow(-Infinity, 1/2)    // Infinity  
(-Infinity) ** 1/2          // Infinity

If you do not use -Infinity in your calculations, it is a safe replacement.

🔧 Options

Nothing.

📚 Further reading

🚀 Version

This rule was introduced in eslint-plugin-math v0.3.0

🔍 Implementation