-1

The default behavior is that trying to access a property of an object that doesn't exist is that it generates an error:

console.log(organization.name)

will generate an error if organization is undefined. Is there a way to somehow change this default behavior and just receive undefined when trying to access a property of a non-existing object? Sometimes it can be helpful rather than remembering to check if object is defined

sir-haver
  • 3,096
  • 7
  • 41
  • 85
  • 1
    Does this answer your question? [How to avoid 'cannot read property of undefined' errors?](https://stackoverflow.com/questions/14782232/how-to-avoid-cannot-read-property-of-undefined-errors) – Douwe de Haan Jun 10 '20 at 11:20

2 Answers2

2

You can use Optional chaining

Optional chaining

The optional chaining operator ?. permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.

const organization = undefined; 
console.log(organization?.name);
Jay
  • 2,826
  • 2
  • 13
  • 28
2

There are multiple solutions :

Using Optional Chaining, or the "I love new features, or I'm using Babel" method:

Though not supported by all browsers, the optional chaining is the cleanest solution. If you need retro compatibility, you should use Babel or some other transpiler, though.

let organization = undefined

console.log(organization?.name)

organization = {name: "foo"}

console.log(organization?.name)

Using try / catch, or the "it works or it doesn't" way:

This solution just attempts to show organization.name, or executes the catch block if it failed.

let organization = undefined

try {
  console.log(organization.name)
} catch(e) {
  console.log("organization.name cannot be accessed") // We end up here
}

organization = {name: "foo"}

try {
  console.log(organization.name) // We end up here
} catch(e) {
  console.log("organization.name cannot be accessed")
}

Using &&, or the "Working our way to the property" approach:

This one returns the value of organization if it is falsy (like undefined, null, false,...), or returns organization.name otherwise.

let organization = undefined

console.log(organization && organization.name) // `organization` is falsy, it will show its value

organization = {name: "foo"}

console.log(organization && organization.name) // `organization` is truthy, it will show `organization.name`
Seblor
  • 6,947
  • 1
  • 25
  • 46