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

  • Vanilla JS toggle
  • Cast Any Value to a Boolean
  • Return every nth element in an array
  • Tell the browser when to run your JavaScript code

Primary Sidebar

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