Try It Editor
Tip: Press
Ctrl/⌘ + Enter
to Run
▶ Run
Reset
Copy
Download
Code
<h2>Assignment Operators</h2> <p>This demo shows <code>=</code>, <code>+=</code>, <code>-=</code>, <code>*=</code>, <code>/=</code>, <code>%=</code>, <code>**=</code>, <code>&=</code>, <code>|=</code>, <code>^=</code>, <code><<=</code>, <code>>>=</code>, <code>>>>=</code>, <code>&&=</code>, <code>||=</code>, <code>??=</code>, and assignment chaining.</p> <h3>1) Basic & Combined Assignment</h3> <pre id="out1" class="out"></pre> <h3>2) Bitwise Assignment</h3> <pre id="out2" class="out"></pre> <h3>3) Logical Assignment (short-circuit)</h3> <pre id="out3" class="out"></pre> <h3>4) Right-to-left Evaluation</h3> <pre id="out4" class="out"></pre> <script> const out1 = document.getElementById('out1'); const out2 = document.getElementById('out2'); const out3 = document.getElementById('out3'); const out4 = document.getElementById('out4'); const L1 = s => out1.textContent += s + '\n'; const L2 = s => out2.textContent += s + '\n'; const L3 = s => out3.textContent += s + '\n'; const L4 = s => out4.textContent += s + '\n'; // 1) Basic + combined let x = 5; L1('Start: x = ' + x); x = 5; L1('x = 5 -> ' + x); x += 3; L1('x += 3 -> ' + x + ' // 8'); x -= 2; L1('x -= 2 -> ' + x + ' // 6'); x *= 4; L1('x *= 4 -> ' + x + ' // 24'); x /= 3; L1('x /= 3 -> ' + x + ' // 8'); x %= 5; L1('x %= 5 -> ' + x + ' // 3'); x **= 3; L1('x **= 3 -> ' + x + ' // 27'); // 2) Bitwise assignment (works on 32-bit integers) let b = 0b1010; // 10 L2('Start (binary): b = 0b1010 // ' + b); b &= 0b0110; L2('b &= 0b0110 -> ' + b + ' // 0b0010 = 2'); b |= 0b0101; L2('b |= 0b0101 -> ' + b + ' // 0b0111 = 7'); b ^= 0b0011; L2('b ^= 0b0011 -> ' + b + ' // 0b0100 = 4'); b <<= 1; L2('b <<= 1 -> ' + b + ' // 0b1000 = 8'); b >>= 2; L2('b >>= 2 -> ' + b + ' // 0b0010 = 2'); b >>>= 1; L2('b >>>= 1 -> ' + b + ' // 0b0001 = 1'); // 3) Logical assignment: ||=, &&=, ??= // ||= assigns when left is falsy; &&= assigns when left is truthy; ??= assigns when left is null/undefined let a1 = 0; // falsy let a2 = 'Hi'; // truthy let a3 = null; // nullish let a4 = 0; // not nullish a1 ||= 42; L3('a1 ||= 42 -> ' + a1 + ' // left was falsy (0), becomes 42'); a2 &&= 'User'; L3("a2 &&= 'User' -> " + a2 + " // left was truthy ('Hi'), becomes 'User'"); a3 ??= 'default'; L3("a3 ??= 'default' -> " + a3 + " // left was null, becomes 'default'"); a4 ??= 100; L3('a4 ??= 100 -> ' + a4 + ' // 0 is not null/undefined, stays 0'); // 4) Right-to-left evaluation let p, q; p = q = 10; // q is set to 10, then p is set to q's value L4('p = q = 10 -> p: ' + p + ', q: ' + q); </script> <style> .out{ background:#0b1020; color:#d1e7ff; padding:10px; border-radius:8px; white-space:pre-wrap; font-family:Consolas,Monaco,monospace; font-size:13px; margin:8px 0 16px; } </style>
Output