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

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • 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:

  • Looping over an object’s keys and values
  • How To Loop Through All The Entries In An Array Using JavaScript
  • Aliases with JavaScript Destructuring
  • Determine whether two values are the same value

Primary Sidebar

JSON Compare

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers
Advertisement