Js Assignment in JavaScript
? JavaScript Assignment
What is Assignment in JavaScript?
Assignment means giving a value to a variable.
Done using the assignment operator
=.
Basic Variable Assignment
let x = 5; // Assign 5 to variable xconst name = "Alice"; // Assign string to constant namevar isActive = true; // Assign boolean to variable isActiveMultiple Assignments
let a, b, c;a = b = c = 10; // Assign 10 to c, then b, then aconsole.log(a, b, c); // 10 10 10Destructuring Assignment (ES6)
Array Destructuring
const arr = [1, 2, 3];const [first, second] = arr;console.log(first, second); // 1 2Object Destructuring
const obj = { name: "Bob", age: 25 };const { name, age } = obj;console.log(name, age); // Bob 25Compound Assignment Operators
Short-hand to assign with an operation:
| Operator | Equivalent To | Example |
|---|---|---|
+= | x = x + y | x += 5 |
-= | x = x - y | x -= 3 |
*= | x = x * y | x *= 2 |
/= | x = x / y | x /= 4 |
%= | x = x % y | x %= 3 |
let num = 10;num += 5; // num is now 15Assignment with Functions
let sayHello = function() { console.log("Hello!");};// Or using arrow functionlet greet = () => console.log("Hi!");If you want, I can explain how assignment works with objects, arrays, or difference between var, let, and const!