CKTIS / JavaScript
Unary negation syntax: prefix minus (`-`)
Unary minus `-x` converts one operand to a numeric value and then negates it. The result is a `Number` or a `BigInt`.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
-x
-(expression)Unary negation syntax puts - before one operand: use -x to negate the value of x, or -(a + b) to negate the entire sum. In -4, - is an operator, not part of the numeric literal. The same token in a - b means subtraction with two operands. Logical !x returns a boolean, while --x decrements the stored value and writes it back. Plain -x does not assign anything.
ECMAScript 2024 uses ToNumeric: it first obtains a primitive value, keeps a BigInt as-is, and otherwise applies ToNumber. So -"4" yields the Number value -4, -"abc" yields NaN, and -Symbol() throws TypeError. Converting an object can call a method such as Symbol.toPrimitive and propagate an exception it throws.
For Number, negation swaps +0 and -0; NaN remains NaN. Object.is distinguishes the two zeros. The result of -4n is a BigInt, and -0n is just 0n: BigInt has no distinct negative zero. The example requires a runtime that supports BigInt literals.
An unparenthesized negation cannot be the left operand of **: -2 ** 2 is a parse-time SyntaxError. Write (-2) ** 2 to square the negative base (4), or -(2 ** 2) to negate the result (-4). A negative exponent on the right is syntactically valid, as in 2 ** -2.
Examples
{
const fromString = -"4";
const fromBigInt = -4n;
const zero = 0;
const negativeZero = -zero;
console.log(`${typeof fromString} ${fromString}`);
console.log(`${typeof fromBigInt} ${fromBigInt}`);
console.log(`${Object.is(negativeZero, -0)} ${Object.is(-negativeZero, +0)}`);
}Result
number -4 bigint -4 true true
The first two lines show the same numeric value in two different types. The last line checks the change from `+0` to `-0` and back.
Related lessons
- JavaScript · Lesson 35 · Advanced · Version: 4
Sources
- ECMAScript 2024 — Unary `-` Operator
- ECMAScript — Unary `-` Operator (living specification)
- ECMAScript 2024 — ToNumeric
- ECMAScript 2024 — ToNumber
- ECMAScript 2024 — Number::unaryMinus
- ECMAScript 2024 — BigInt::unaryMinus
- ECMAScript 2024 — Exponentiation Operator
- ECMAScript 2024 — Object.is
- ECMAScript 2024 — Number::sameValue