JD Dasar: 28. Operator in

by istiq20

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Operator in</title>
  </head>
  <body>
    <script>
      // mengecek apakah sebuah properti di dalam object ada atau tidak
      const car = {
        brand: "Avanza",
        color: "Red",
      };

      const resultIn = "brand" in car;

      document.writeln(`<p>${resultIn}</p>`); // true

      const person = {
        firstName: "Eko",
        lastName: "Khannedy",
      };

      if ("firstName" in person) {
        alert(`Hello ${person.firstName}`);
      } else {
        alert("Hello");
      }

      // in operator undefined/null property
      const student = {
        firstName: "Eko",
        middleName: undefined,
        lastName: "Khannedy",
      };

      if ("middleName" in student) {
        alert(`Hello ${student.middleName}`);
      } else {
        alert("Hello Student");
      }

      const names = [null, "Kurniawan", null];
      const result = 0 in names;
      document.writeln(`<p>${result}</p>`);
    </script>
  </body>
</html>