• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Forum
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Optional Chaining to Prevent Crashes

Optional Chaining to Prevent Crashes

Optional Chaining to Prevent Crashes

If you access an undefined property, an error is produced. This is where optional chaining comes to the rescue.

Using the optional chaining operator ?. when the property is not defined, undefined is returned instead of an error. This prevents your code from crashing.

For example:

const student = {
  name: "Matt",
  age: 27,
  address: {
    state: "New York"
  },
};

// LONG FORM
console.log(student && student.address && student.address.ZIPCode); // Doesn't exist - Returns undefined

// SHORTHAND
console.log(student?.address?.ZIPCode); // Doesn't exist - Returns undefined

Source

https://medium.com/geekculture/20-javascript-snippets-to-code-like-a-pro-86f5fda5598e

Miscellaneous

Related Snippets:

  • Aliases with JavaScript Destructuring
  • How to loop through arrays and array-like objects in JavaScript
  • Check if the given number falls within the given range
  • Return all elements in an array except for the first one

Primary Sidebar

FREE UPDATES!

Get the latest updates in your inbox for FREE!

Popular Posts

Story Generator

IP Grabber

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2022 JavaScriptSource.com

  • About
  • Privacy Policy
  • Submit
  • FAQ
  • Jobs For Developers
  • Contact Us