For AI agents: the complete documentation index is available at https://rslint.rs/llms.txt, the full documentation bundle is available at https://rslint.rs/llms-full.txt, and this page is available as Markdown at https://rslint.rs/rules/unicorn/prefer-math-abs.md.
close

prefer-math-abs

Unreleased

Configuration

rslint.config.ts
import { defineConfig, unicornPlugin } from '@rslint/core';

export default defineConfig([
  unicornPlugin.configs.recommended,
  {
    rules: {
      'unicorn/prefer-math-abs': 'error',
    },
  },
]);

Rule details

Prefer Math.abs() for manual absolute value expressions and checks that compare a value against both a limit and its negation. The rule recognizes negation written as -value, 0 - value, or multiplication by -1. It skips operands it recognizes as BigInt because Math.abs() throws on BigInt.

The rule offers editor suggestions. Review them if your code depends on signed zero or non-number operands. For example, with value = -0, the expression value < 0 ? -value : value yields -0 and Math.abs(value) yields 0. Math.abs() also coerces its operand to a number. Suggestions are withheld when the rewrite would remove comments or change how often a member is read.

Incorrect

const absolute = value < 0 ? -value : value;
const magnitude = value <= 0 ? 0 - value : value;
const distance = value > 0 ? value : -value;

if (number > MAXIMUM || number < -MAXIMUM) {
}

Correct

const absolute = Math.abs(value);

if (Math.abs(number) > MAXIMUM) {
}

Options

This rule has no options.

Differences from upstream

  • Rslint reports the expression and withholds the suggestion if a local binding shadows Math or languageOptions.globals disables it.
  • Rslint skips additional cases where an operand is known to be a BigInt. For example, it skips a check on a property inferred to be bigint from const state = { offset: 1n } or a value cast with JSDoc /** @type {bigint} */. It also recognizes generic aliases such as Id<bigint> with type Id<T> = T in files without a TypeScript project. This includes defaults such as type Value<T = DefaultValue> = T with type DefaultValue = Value<bigint>.
  • Rslint can report a manual absolute value for the result of a local function named BigInt that returns a number, such as function BigInt(value) { return Number(value); }.

Original documentation