</> Code Corner

JavaScript · JS Tutorial · Lesson 35

JS Destructuring

Unpack values from arrays and objects; spread and rest.

Destructuring assignment unpacks values from arrays and properties from objects into variables.

Example

<p id="demo"></p>
<script>
const person = { firstName: "John", lastName: "Doe", age: 50 };
const { firstName, age, country = "US" } = person;
const fruits = ["Bananas", "Oranges", "Apples", "Mangos"];
const [first, , third, ...rest] = fruits;
const more = [...fruits, "Kiwi"];          // spread
let a = 1, b = 2;
[a, b] = [b, a];                           // swap
document.getElementById("demo").innerHTML =
  firstName + " " + age + " " + country + "<br>" + first + ", " + third + ", rest: " + rest +
  "<br>more: " + more.length + " items<br>a = " + a + ", b = " + b;
</script>
Tip: ... is called the spread operator when it expands values and the rest operator when it collects them.

Keep reading “JS Destructuring”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋