Unary-Negation (-)

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Der Unary-Negation-Operator (-) steht vor seinem Operanden und negiert diesen.

Probieren Sie es aus

const x = 4;
const y = -x;

console.log(y);
// Expected output: -4

const a = "4";
const b = -a;

console.log(b);
// Expected output: -4

Syntax

js
-x

Beschreibung

Der - Operator ist für zwei Typen von Operanden überladen: Zahl und BigInt. Er zwingt den Operanden zunächst zu einem numerischen Wert und überprüft dessen Typ. Wenn der Operand zu einem BigInt wird, wird die BigInt-Negation durchgeführt; andernfalls erfolgt die Zahlen-Negation.

Beispiele

Zahlen negieren

js
const x = 3;
const y = -x;
// y is -3; x is 3

Nicht-Zahlen negieren

Der Unary-Negation-Operator kann eine Nicht-Zahl in eine Zahl umwandeln.

js
const x = "4";
const y = -x;

// y is -4

BigInts können mit dem Unary-Negation-Operator negiert werden.

js
const x = 4n;
const y = -x;

// y is -4n

Spezifikationen

Specification
ECMAScript® 2025 Language Specification
# sec-unary-minus-operator

Browser-Kompatibilität

BCD tables only load in the browser

Siehe auch