Cannot read property keycode of undefined at userchoosing

Last updated: Mar 3, 2024
Reading time · 6 min

banner

# [Solved] Cannot read Properties of Undefined in JavaScript

The "Cannot read properties of undefined" error occurs for multiple reasons:

  1. Accessing a property on a variable that stores an undefined value.
  2. Accessing a property on a DOM element that doesn't exist.
  3. Inserting the JS script tag above the HTML where the DOM elements are declared.

cannot read property of undefined

Most commonly, the error occurs if you try to access a property on a variable that has a value of undefined .

Copied!
const person = undefined; // ⛔️ Cannot read properties of undefined (reading 'name') person.name;

We attempted to access the name property on an undefined value which caused the error.

# Use the optional chaining (?.) operator

If the variable is undefined or null , the operator short-circuits instead of throwing an error.

Copied!
const person = undefined; // ✅ Using optional chaining console.log(person?.name); // 👉️ undefined console.log(person?.name?.first); // 👉️ undefined // ✅ Using if / else if (person?.name) console.log(person.name); > else // 👇️ this runs console.log('person.name not found'); > // ✅ Using logical AND (&&) operator console.log(person && person.name); // 👉️ undefined

use optional chaining operator

The code for this article is available on GitHub

The optional chaining (?.) operator allows us to access a property on an object without throwing an error if the reference is invalid.

Instead of throwing an error, the optional chaining (?.) operator short-circuits returning undefined if the reference is equal to undefined or null .

# Using the Logical AND operator

You can also use the logical AND (&&) operator in a similar way.

Copied!
const person = undefined; console.log(person && person.name); // 👉️ undefined // 👇️ undefined console.log(person && person.name && person.name.first);

using logical and operator

The code for this article is available on GitHub

The logical AND (&&) operator doesn't evaluate the value to the right if the value to the left is falsy (e.g. undefined ).

You can use the logical AND (&&) operator in a similar way to how the optional chaining (?.) operator is used.

Copied!
let person; console.log(person); // 👉️ undefined // ✅ using optional chaining if (person?.address?.country) console.log(person.address.country); > // ✅ using logical AND (&&) if (person && person.address && person.address.country) console.log(person.address.country); >

# Accessing an array at an index that doesn't exist

A common source of undefined values is accessing an array at an index that doesn't exist.

Use the optional chaining (?.) operator or the logical AND (&&) operator to make sure the array index exists before accessing the property.

Copied!
const arr = []; // ⛔️ Cannot read properties of undefined (reading 'name') console.log(arr[0].name); // ❌ Bad console.log(arr[0]?.name); // ✅ Good console.log(arr[0] && arr[0].name); // ✅ Good

accessing array at index that does not exist

The code for this article is available on GitHub Accessing an array at an index that doesn't exist returns undefined .

Use the same approach if you have to access nested array elements at indices that might not exist.

Copied!
const arr = [['a', 'b', 'c']]; console.log(arr?.[0]); // 👉️ ['a', 'b', 'c'] console.log(arr?.[0]?.[0]); // 👉️ a console.log(arr?.[0]?.[0]?.[1]); // 👉️ undefined console.log(arr?.[0]?.[0]?.[1]?.[0]); // 👉️ undefined

You can also use the optional chaining (?.) operator to provide a value to be returned if the variable or its property returned undefined .

Copied!
let person; const name = person?.name ?? 'default'; console.log(name); // 👉️ 'default' const country = person?.address?.country ?? 'default'; console.log(country); // 👉️ 'default'
The person variable stores a value of undefined because we didn't initialize it.

If accessing the name property on the person variable returns undefined , the value to the left of the nullish coalescing (??) operator is returned.

# Provide a fallback value for when the variable stores an undefined value

An alternative way to solve the error is to provide a fallback value if the variable stores a falsy value (e.g. undefined ).

Copied!
const name = undefined; const result1 = (name ?? 'bobby').toUpperCase(); console.log(result1); // 👉️ BOBBY const obj = undefined; const result2 = (obj ?? name: 'bobby'>).name; console.log(result2); // 👉️ bobby

provide fallback value for when variable stores undefined

The code for this article is available on GitHub

The nullish coalescing operator (??) returns the value to the right if the value to the left is nullish ( null or undefined ).

In all other cases, it returns the value to the left.

Another common reason for getting the error is accessing a property on DOM element that doesn't exist.

# Track down where the variable got assigned an undefined value

A variable that has been declared but hasn't been given a value has a value of undefined in JavaScript.

Copied!
let employee; console.log(employee); // 👉️ undefined // ⛔️ TypeError: Cannot read properties of undefined (reading 'name') console.log(employee.name);

We declared the employee variable but didn't assign a value to it, so it stores an undefined value.

Instead, initialize the variable when declaring it.

Copied!
let employee = >; console.log(employee.name); // 👉️ undefined

We set the employee variable to an empty object, but you can use any other value that suits your use case, e.g. an empty array [] or an empty string "" .

You also get an undefined value when you access an array at an index that doesn't exist.

Copied!
let employees = []; console.log(employees[1]); // 👉️ undefined // ⛔️ TypeError: Cannot read properties of undefined (reading 'push') console.log(employees[1].push('a'));

If you need to add an element to the array, call the push() method on the array without accessing it at a specific index.

Copied!
let employees = []; employees.push('bobby'); employees.push('hadz'); employees.push('com'); // 👇️ [ 'bobby', 'hadz', 'com' ] console.log(employees);

If you meant to access a property on a specific array element, use the optional chaining operator.

Copied!
let employees = ['a', 'b']; const result = employees[100]?.toUpperCase(); console.log(result); // 👉️ undefined

If the array element at the specified index doesn't exist, the optional chaining operator returns undefined instead of throwing an error.

If the error persists, you have to track down where the variable got assigned an undefined value.

A common source of undefined values is assigning the output of a function that doesn't return anything to a variable.

Many built-in methods that mutate an object in place return undefined .

All JavaScript functions that don't return a value return undefined .

You might be accessing an array at an index that doesn't exist or a non-existent property in an object.

# Make sure the DOM elements you are accessing exist

To solve the "Cannot read properties of undefined" error, make sure that the DOM element you are accessing exists.

The error is often thrown when trying to access a property at a non-existent index after using the getElementsByClassName() method.

Copied!
const boxes = document.getElementsByClassName('does-not-exist'); console.log(boxes); // [] // ⛔️ Cannot read properties of undefined (reading 'innerHTML') console.log(boxes[0].innerHTML);

Instead, correct the class name and use the optional chaining (?.) operator to check if the DOM element at index 0 contains the property.

Copied!
const boxes = document.getElementsByClassName('does-not-exist'); console.log(boxes); // [] // ✅ check for existence of property if (boxes[0]?.innerHTML) console.log(boxes[0].innerHTML); > else // 👇️ this runs console.log('element does not exist'); >