pFad - Phone/Frame/Anonymizer/Declutterfier! Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

URL: http://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Logical_OR_assignment

https://developer.mozilla.org/favicon.ico" />

このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

論理和代入演算子 (||=)

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2020年9月.

論理和代入演算子 (||=) は、左オペランドが偽値の場合にのみ右オペランドを評価し、左オペランドに代入します。

試してみましょう

const a = { duration: 50, title: "" };

a.duration ||= 10;
console.log(a.duration);
// 予想される結果: 50

a.title ||= "title is empty.";
console.log(a.title);
// 予想される結果: "title is empty."

構文

js
x ||= y

解説

論理和代入演算子は短絡評価を行うため、x ||= yx || (x = y) と同等です。ただし、式 x は一度だけ評価されます。

左辺が偽値でない場合、論理和演算子の短絡が発生するため代入は実行されません。例えば、 xconst であっても、以下のコードはエラーが発生しません。

js
const x = 0;
x ||= 2;

次のコードもセッターを起動しません。

js
const x = {
  get value() {
    return 1;
  },
  set value(v) {
    console.log("セッターが呼び出されました");
  },
};

x.value ||= 2;

そして、常に代入が行われる以下と等価ではありません。

js
const x = 1;
x ||= console.log("y が評価されました");
// 何もログ出力されない

既定の内容を設定する

"lyrics" 要素が空の場合は、既定値を表示します。

js
document.getElementById("lyrics").textContent ||= "No lyrics.";

ここでの短絡評価は、要素が不必要に更新されることがなく、追加のパースやレンダリング作業、フォーカスの損失などの望ましくない副作用を引き起こすことがないので、特に有益です。

注意: チェック対象の API が返す値に注意してください。空の文字列(偽値)が返される場合は、||= を使用する必要があります。それ以外の場合 (返値が null または undefined の場合) は ??= 演算子を使用してください。

仕様書

Specification
ECMAScript® 2026 Language Specification
# sec-assignment-operators

ブラウザーの互換性

関連情報

pFad - Phonifier reborn

Pfad - The Proxy pFad © 2024 Your Company Name. All rights reserved.





Check this box to remove all script contents from the fetched content.



Check this box to remove all images from the fetched content.


Check this box to remove all CSS styles from the fetched content.


Check this box to keep images inefficiently compressed and original size.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy