JS Dasar: 62. Destructuring

by istiq20

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Destructuring</title>
  </head>
  <body>
    <script>
      {
        // mengambil data di array
        const names = ["Eko", "Kurniawan", "Khannedy"];
        const firstName = names[0];
        const middleName = names[1];
        const lastName = names[2];

        console.log(firstName); // Eko
        console.log(middleName); // Kurniawan
        console.log(lastName); // Khannedy
      }

      {
        // destructuring array
        const names = ["Eko", "Kurniawan", "Khannedy", "Budi", "Joko"];
        let [firstName, middleName, lastName, ...others] = names;

        console.log(firstName); // Eko
        console.log(middleName); // Kurniawan
        console.log(lastName); // Khannedy
        console.log(others); // ['Budi', 'Joko']
      }

      {
        // mengambil data di object
        const person = {
          firstName: "Eko",
          lastName: "Khannedy",
          address: {
            street: "Jalan Belum Ada",
            city: "Jakarta",
            country: "Indonesia",
          },
          hobby: "Game",
          channel: "Programmer Zaman Now",
        };

        const firstName = person.firstName;
        const lastName = person.lastName;

        console.log(firstName); // Eko
        console.log(lastName); // Khannedy
      }

      {
        // destructuring object
        const person = {
          firstName: "Budi",
          lastName: "Nugraha",
          address: {
            street: "Jalan Kenangan",
            city: "Bekasi",
            country: "Indonesia",
          },
          hobby: "Bermusik",
          channel: "Tutorial bermain gitar",
        };

        const { firstName, lastName, address, ...others } = person;

        console.log(firstName); // Budi
        console.log(lastName); // Nugraha
        console.log(address); // {street: 'Jalan Kenangan', city: 'Bekasi', country: 'Indonesia'}
        console.log(others); //...