単項マイナス演算子 (-)
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
単項マイナス演算子 (-
) はオペランドの前に置かれ、符号を反転します。
試してみましょう
const x = 4;
const y = -x;
console.log(y);
// 予想される結果: -4
const a = "4";
const b = -a;
console.log(b);
// 予想される結果: -4
構文
js
-x
解説
-
演算子は、数値と長整数の 2 種類のオペランドに対してオーバーロードされています。最初のオペランドを数値に型変換を行い、その型を検査します。オペランドが長整数になった場合は長整数の否定を実行し、そうでない場合は数値の否定を実行します。
例
>数値の符号を反転
js
const x = 3;
const y = -x;
// y is -3; x is 3
数値以外の符号を反転
単項マイナス演算子は、数値でないものを数値に変換することができます。
js
const x = "4";
const y = -x;
// y = -4
長整数は、単項マイナス演算子を使用して符号を反転することができます。
js
const x = 4n;
const y = -x;
// y is -4n
仕様書
Specification |
---|
ECMAScript® 2026 Language Specification> # sec-unary-minus-operator> |
ブラウザーの互換性
Loading…