Skip to content

Instantly share code, notes, and snippets.

@Mahdhir
Last active November 2, 2020 15:57
Show Gist options
  • Save Mahdhir/e7ff3ea73d85ccb913b9ca18e3497f23 to your computer and use it in GitHub Desktop.
Save Mahdhir/e7ff3ea73d85ccb913b9ca18e3497f23 to your computer and use it in GitHub Desktop.

Revisions

  1. Mahdhir revised this gist Nov 2, 2020. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion optional-chaining-before.js
    Original file line number Diff line number Diff line change
    @@ -28,5 +28,5 @@ if (book && book.weight && book.weight.version3 && book.weight.version3.value) {
    }

    //Accessing without checking
    console.log(book.weight.version3.value;
    console.log(book.weight.version3.value);
    //error
  2. Mahdhir created this gist Oct 1, 2020.
    32 changes: 32 additions & 0 deletions optional-chaining-before.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    let book = {
    name: "Harry Potter 1",
    price: {
    value: 50,
    currency: "EUR"
    },
    ISBN: "978-7-7058-9615-2",
    weight: {
    version1: {
    value: 550,
    unit: 'g'
    },
    version2: {
    value: 690,
    unit: 'g'
    }
    }
    }

    if (book && book.weight && book.weight.version2 && book.weight.version2.value) {
    //Do something with book.weight.version2.value
    console.log(book.weight.version2.value);
    }

    if (book && book.weight && book.weight.version3 && book.weight.version3.value) {
    //Since there is no version 3, this block would not run and throw any errors
    console.log(book.weight.version3.value);
    }

    //Accessing without checking
    console.log(book.weight.version3.value;
    //error