-2

Some simple code that I feel should work:

function getUser(id) {
  var user;
  // get user from DB
  return user;
}

var user = getUser(1);

var uname = user.getName();

console.log(uname);

// user is expected to be an instance of the following class:
class User {#
  id = 1;#
  first = 'Bob';#
  last = 'Test'
  /*
   * # here denotes a private variable. If the syntax is not available,
   * simply use an underscore `var _`, so that it becomes
   * var _id = 1;
   * var _first = 'Bob';
   * var _last = 'Test';
   * They will no longer be true private variables, but it should be close enough.
   */
  constructor() {}
  get id() {
    return this.#id;
  }
  set id(value) {
    this.#id = value;
  }
  get firstName() {
    return this.#first;
  }
  set firstName(value) {
    this.#first = value;
  }
  get lastName() {
    return this.#last;
  }
  set lastName(value) {
    this.#last = value;
  }
  getName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

The error is:

Uncaught TypeError: Cannot read properties of undefined (reading 'getName')

What is going on?


A similar error occurs when I use a service (and fetch to get the user):

async function getUser(id) {
  // get user from API, using fetch from a suitable library (not relevant to question)
  let user;
  try {
    const response = await fetch(`/users/${id}`);
    user = await response.json();
  } catch {}
  return user;
}

(async function () {
  const user = await getUser(1);
  const uname = user.getName();
  console.log(uname);
})();

// user is expected to be an instance of the following class:
class User {
  #id = 1;
  #first = 'Bob';
  #last = 'Test';
  /*
   * # here denotes a private variable. If the syntax is not available,
   * simply use an underscore `var _`, so that it becomes
   * var _id = 1;
   * var _first = 'Bob';
   * var _last = 'Test';
   * They will no longer be true private variables, but it should be close enough.
   */
  constructor() {}
  get id() {
    return this.#id;
  }
  set id(value) {
    this.#id = value;
  }
  get firstName() {
    return this.#first;
  }
  set firstName(value) {
    this.#first = value;
  }
  get lastName() {
    return this.#last;
  }
  set lastName(value) {
    this.#last = value;
  }
  getName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

You cannot see the error in the Stack Snippet console but must open your Developer Tools to see it there.

The error simply includes a parenthetical "(in promise)" in the error text:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'getName')

4
  • 1
    What makes you think the user should have a getId() method? If this is meant to be a canonical Q+A, the question and its assumptions are rather irritating and misleading. I don't see how anyone would be getting anything useful from this.
    – connexo
    Oct 17, 2022 at 21:41
  • I don't see how anyone could not get anything about the error it is asking about. Feel free to suggest constructive changes rather than only emotional criticisms. Oct 17, 2022 at 21:57
  • 1
    @HereticMonkey this is a much-needed "dup magnet". If anything, I would change the '' in the title to maybe 'something' or 'xyz'. Also, a second code example with a short async section might be good too, for the extremely common case, and yes it's covered by another dup magnet I realize.
    – Pointy
    Oct 17, 2022 at 23:48
  • @Pointy Added async example, although Stack Snippets makes it hard :(. Feel free to edit if you know of a better way of making the example work. Oct 19, 2022 at 17:11

1 Answer 1

1

The function that is supposed to be setting user to an object with a getName() method is instead returning undefined. That value does not have any properties or methods, so it throws the error shown.

There are several ways around the error, but it comes down to deciding what you want to do when getUser returns undefined. You can throw a different, more informative error. Either at the time you know you didn't get a User back from getUser(1):

class User {
  #id = 1;
  #first = 'Bob';
  #last = 'Test'
  constructor() {}
  get id() {
    return this.#id;
  }
  set id(value) {
    this.#id = value;
  }
  get firstName() {
    return this.#first;
  }
  set firstName(value) {
    this.#first = value;
  }
  get lastName() {
    return this.#last;
  }
  set lastName(value) {
    this.#last = value;
  }
  getName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

function getUser(id) {
  // get user from DB
  var user;
  return user;
}

var user = getUser(1);

if (!(user instanceof User)) {
  throw new Error(`The value returned from getUser(1): ${JSON.stringify(user)} was not a User.`);
}

var uid = user.getName();

console.log(uid);

Or later, via the "optional chaining" operator:

class User {
  #id = 1;
  #first = 'Bob';
  #last = 'Test'
  constructor() {}
  get id() {
    return this.#id;
  }
  set id(value) {
    this.#id = value;
  }
  get firstName() {
    return this.#first;
  }
  set firstName(value) {
    this.#first = value;
  }
  get lastName() {
    return this.#last;
  }
  set lastName(value) {
    this.#last = value;
  }
  getName() {
    return `${this.firstName} ${this.lastName}`;
  }
}


function getUser(id) {
  // get user from DB
  var user;
  return user;
}

var user = getUser(1);

var uname = user?.geName();
// If your environment does not allow for optional chaining, simply use &&:
// var uname = user && user.getName();

if (typeof uname !== 'string') {
  throw new Error(`The value returned from getUser(1).getName(): ${JSON.stringify(uname)} was not a string.`);
}

console.log(uname);

You can also just choose to pass the problem on to the next consumer. So, assuming the code is part of a tautological getUserId(userId) function, you could pass the undefined on, again, via our friend the optional chaining operator ?..

class User {
  #id = 1;
  #first = 'Bob';
  #last = 'Test'
  constructor() {}
  get id() {
    return this.#id;
  }
  set id(value) {
    this.#id = value;
  }
  get firstName() {
    return this.#first;
  }
  set firstName(value) {
    this.#first = value;
  }
  get lastName() {
    return this.#last;
  }
  set lastName(value) {
    this.#last = value;
  }
  getName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

function getUser(id) {
  // get user from DB
  var user;
  return user;
}

function getUserName(id) {
  var user = getUser(id);
  var uname = user?.getName();
  return uname;
}

console.log(getUserName(1));

3
  • Common mistake. The function is creating a variable, that is automatically undefined because nothing comes after it. Then it returns it and the function is stored in a user variable, so since the function returned undefined, the variable user is undefined. Oct 17, 2022 at 21:36
  • @ParkingMaster I'm well aware of the issue. I answered it myself, after all :). I couldn't find a good q&a pair about this common problem that didn't bring in some other library or DOM or something else. Oct 17, 2022 at 21:39
  • Oh, I didn't know this was a q&a pair. I thought someone else answered it haha Oct 17, 2022 at 21:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.