Reference : TypeError: Cannot read property [property name here] from undefined
Asked Answered
C

1

0

Derived from Canonical question for TypeError Cannot [call method / read property / set property] of null in Google Apps Script


Proposed reference for questions like :

Contractor answered 18/10, 2022 at 9:53 Comment(1)
This question was posted after discussion on metaIncudes
C
1

Description

The error message indicates that you are trying to access a property on an Object instance, but during runtime the value actually held by a variable is a special data type undefined.

See key terms definition at the bottom.

Causes:

  • The error occurs when accessing properties of an object, which does not exist.

    If a property doesn't exist in a object, accessing that property results in undefined and eventually a type error, if undefined is accessed like a real object.. This maybe due to typos or using case insensitive names to access a property. A variation of this error with a numeric value in place of property name indicates that an instance of Array was expected. As arrays in JavaScript are objects, everything mentioned here is true about them as well.

const obj = {a:1};
const b = obj.b;//undefined because b isn't available on obj. But doesn't throw a error
console.log(b.toString())//Throws type error 
  • Accessing Arrays index greater than the last element's index

    Array.prototype.length returns the number of elements of the Array. This number is always greater than the last element's index, as JavaScript uses 0 based indices. Accessing any index greater than or equal to the length of the array results in this type error. Eg, when accessing 3rd element in a array of length 3,

const a = [[1],[2],[3]];
const getElement3 = a[3];//undefined,because `3`'s index is ``2`` not `3`;But doesn't throw a error
console.log(getElement3[0])//Throws type error
  • Accessing Event objects without a event:

    There is a special case of dynamically constructed objects such as event objects that are only available in specific contexts like making an HTTP request to the app or invoking a function via time or event-based trigger.

The error is a TypeError because an "object" is expected, but "undefined" is received

How to fix

  1. Using default values
    Nullish Coalescing operator ?? operator in JavaScript evaluates the right-hand side if the left-hand is null or undefined. An expression like (myVar ?? {}).myProp (or (myVar ?? [])[index] for arrays) will guarantee that no error is thrown, if the property is at least undefined.

    One can also provide default values: (myVar ?? { myProp : 2 }) guarantees accessing myProp to return 2 by default. Same goes for arrays: (myVar ?? [1,2,3]).

  2. Checking for type
    Especially true for the special case, typeof operator combined with an if statement and a comparison operator will either allow a function to run outside of its designated context (i.e. for debugging purposes) or introduce branching logic depending on whether the object is present or not.

    One can control how strict the check should be:

    • lax ("not undefined"): if(typeof myVar !== "undefined") { //do something; }
    • strict ("proper objects only"): if(typeof myVar === "object" && myVar) { //do stuff }

Key Terms

Object
It's one of the JavaScript data types.
undefined
It's one of the JavaScript primitive data types.

To learn about the very basics of JavaScript data types and objects see What are JavaScript Data Types? and What exactly is an object? [JavaScript].


Original revision extracted from here (Credit to @OlegValter)

Contractor answered 18/10, 2022 at 9:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.