javascript
examples
examples.js⚡javascript
/**
* ============================================
* 3.4 Assignment Operators - Examples
* ============================================
*/
// ============================================
// 1. BASIC ASSIGNMENT
// ============================================
console.log('=== Basic Assignment ===');
// Simple assignment
let x = 10;
let name = 'John';
let isActive = true;
console.log('x:', x, 'name:', name, 'isActive:', isActive);
// Assign expression result
let sum = 5 + 3;
let product = 4 * 6;
console.log('sum:', sum, 'product:', product);
// Assignment returns the value
let a, b;
b = a = 5;
console.log('a:', a, 'b:', b); // Both are 5
// ============================================
// 2. REFERENCE VS VALUE
// ============================================
console.log('\n=== Reference vs Value ===');
// Primitives - copy by value
let num1 = 10;
let num2 = num1;
num2 = 20;
console.log('num1:', num1, 'num2:', num2); // 10, 20
// Objects - copy by reference
let obj1 = { value: 10 };
let obj2 = obj1;
obj2.value = 20;
console.log('obj1.value:', obj1.value); // 20 (affected!)
// Creating a copy
let obj3 = { ...obj1 }; // Shallow copy
obj3.value = 30;
console.log('obj1.value:', obj1.value, 'obj3.value:', obj3.value);
// ============================================
// 3. ARITHMETIC ASSIGNMENT
// ============================================
console.log('\n=== Arithmetic Assignment ===');
// Addition assignment
let count = 10;
count += 5;
console.log('10 += 5 →', count); // 15
// String concatenation
let message = 'Hello';
message += ' World';
console.log("'Hello' += ' World' →", message);
// Subtraction assignment
let balance = 100;
balance -= 25;
console.log('100 -= 25 →', balance); // 75
// Multiplication assignment
let value = 5;
value *= 3;
console.log('5 *= 3 →', value); // 15
// Division assignment
let total = 100;
total /= 4;
console.log('100 /= 4 →', total); // 25
// Modulo assignment
let remainder = 17;
remainder %= 5;
console.log('17 %= 5 →', remainder); // 2
// Exponentiation assignment
let base = 2;
base **= 3;
console.log('2 **= 3 →', base); // 8
// ============================================
// 4. BITWISE ASSIGNMENT
// ============================================
console.log('\n=== Bitwise Assignment ===');
// Bitwise AND
let bits1 = 0b1100; // 12
bits1 &= 0b1010; // 0b1000 = 8
console.log('0b1100 &= 0b1010 →', bits1);
// Bitwise OR
let bits2 = 0b1100; // 12
bits2 |= 0b0011; // 0b1111 = 15
console.log('0b1100 |= 0b0011 →', bits2);
// Bitwise XOR
let bits3 = 0b1100; // 12
bits3 ^= 0b1010; // 0b0110 = 6
console.log('0b1100 ^= 0b1010 →', bits3);
// Left shift
let shift1 = 5;
shift1 <<= 2; // 20
console.log('5 <<= 2 →', shift1);
// Right shift
let shift2 = 20;
shift2 >>= 2; // 5
console.log('20 >>= 2 →', shift2);
// ============================================
// 5. LOGICAL ASSIGNMENT
// ============================================
console.log('\n=== Logical Assignment ===');
// Logical AND assignment (&&=)
console.log('--- AND Assignment (&&=) ---');
let la1 = 1;
la1 &&= 5;
console.log('1 &&= 5 →', la1); // 5
let la2 = 0;
la2 &&= 5;
console.log('0 &&= 5 →', la2); // 0 (not assigned)
// Logical OR assignment (||=)
console.log('\n--- OR Assignment (||=) ---');
let lo1 = 0;
lo1 ||= 10;
console.log('0 ||= 10 →', lo1); // 10
let lo2 = 5;
lo2 ||= 10;
console.log('5 ||= 10 →', lo2); // 5 (not assigned)
// Nullish coalescing assignment (??=)
console.log('\n--- Nullish Assignment (??=) ---');
let ln1 = null;
ln1 ??= 'default';
console.log("null ??= 'default' →", ln1); // "default"
let ln2 = 0;
ln2 ??= 10;
console.log('0 ??= 10 →', ln2); // 0 (not assigned, 0 is not nullish)
let ln3 = '';
ln3 ??= 'default';
console.log("'' ??= 'default' →", ln3); // "" (not assigned)
// ============================================
// 6. ARRAY DESTRUCTURING
// ============================================
console.log('\n=== Array Destructuring ===');
// Basic
let [first, second, third] = [1, 2, 3];
console.log('Basic:', first, second, third);
// Skip elements
let [one, , three] = [1, 2, 3];
console.log('Skip:', one, three);
// Rest pattern
let [head, ...tail] = [1, 2, 3, 4, 5];
console.log('Head:', head, 'Tail:', tail);
// Default values
let [d1 = 10, d2 = 20] = [5];
console.log('Defaults:', d1, d2); // 5, 20
// Swap variables
let m = 1,
n = 2;
console.log('Before swap:', m, n);
[m, n] = [n, m];
console.log('After swap:', m, n);
// ============================================
// 7. OBJECT DESTRUCTURING
// ============================================
console.log('\n=== Object Destructuring ===');
// Basic
let { name: userName, age } = { name: 'John', age: 30 };
console.log('Basic:', userName, age);
// Default values
let { title = 'Untitled', author = 'Unknown' } = { title: 'JS Guide' };
console.log('Defaults:', title, author);
// Nested
let {
address: { city },
} = { address: { city: 'NYC' } };
console.log('Nested:', city);
// Rest pattern
let { id, ...rest } = { id: 1, name: 'John', age: 30 };
console.log('ID:', id, 'Rest:', rest);
// ============================================
// 8. FUNCTION PARAMETER DESTRUCTURING
// ============================================
console.log('\n=== Function Parameter Destructuring ===');
// Array parameter
function sumArray([a, b, c]) {
return a + b + c;
}
console.log('Sum array:', sumArray([1, 2, 3]));
// Object parameter with defaults
function createUser({ name = 'Anonymous', age = 0 } = {}) {
return { name, age };
}
console.log('Create user:', createUser({ name: 'Jane' }));
console.log('Create user (empty):', createUser());
// ============================================
// 9. CHAINED ASSIGNMENT
// ============================================
console.log('\n=== Chained Assignment ===');
// Multiple variables
let ca, cb, cc;
ca = cb = cc = 10;
console.log('Chained:', ca, cb, cc);
// With expression
let cx, cy;
cx = cy = 5 + 3;
console.log('Expression:', cx, cy);
// Caution with objects!
let o1, o2, o3;
o1 = o2 = o3 = { value: 10 };
o1.value = 20;
console.log('Object chaining (same ref):', o1.value, o2.value, o3.value);
// ============================================
// 10. COMMON PATTERNS
// ============================================
console.log('\n=== Common Patterns ===');
// Counter
let counter = 0;
counter += 1;
counter += 1;
counter += 1;
console.log('Counter:', counter);
// Accumulator
let accumulator = 0;
let numbers = [1, 2, 3, 4, 5];
for (let num of numbers) {
accumulator += num;
}
console.log('Accumulator:', accumulator);
// String building
let result = '';
result += 'Hello';
result += ' ';
result += 'World';
console.log('String building:', result);
// Conditional default
function configure(options = {}) {
options.timeout ??= 5000;
options.retries ??= 3;
options.debug ??= false;
return options;
}
console.log('Configure:', configure({ timeout: 1000 }));
// Safe increment (initialize if needed)
let stats = {};
stats.views ??= 0;
stats.views += 1;
stats.views += 1;
console.log('Safe increment:', stats);
// ============================================
// 11. PRACTICAL EXAMPLES
// ============================================
console.log('\n=== Practical Examples ===');
// Shopping cart
let cart = {
items: [],
total: 0,
};
function addItem(item) {
cart.items = [...cart.items, item];
cart.total += item.price;
}
addItem({ name: 'Widget', price: 9.99 });
addItem({ name: 'Gadget', price: 24.99 });
console.log('Cart:', cart);
// Configuration merging
function mergeConfig(userConfig) {
let config = { timeout: 5000, retries: 3 };
config = { ...config, ...userConfig };
return config;
}
console.log('Merged config:', mergeConfig({ timeout: 1000 }));
// Extracting data with destructuring
let response = {
data: { user: { id: 1, name: 'John' } },
status: 200,
};
let {
data: {
user: { name: extractedName },
},
status,
} = response;
console.log('Extracted:', extractedName, status);
// Multiple return values
function getMinMax(arr) {
return [Math.min(...arr), Math.max(...arr)];
}
let [min, max] = getMinMax([3, 1, 4, 1, 5, 9]);
console.log('Min/Max:', min, max);
console.log('\n=== Examples Complete ===');