Removing an item causes an error

I believe the piece of code responsible is right here in my equip function and the problem is trying to read the id of the item if I remove it.

I have classes changing with a particular item in a slot so when nothing is there it needs to revert back to the default class.

Code:
    var itemHolder = this.actor().equips()[5].id;
 
    if(this.actor().equips()[5] == null){ //empty
    this.actor().changeClass(5, true);
    }
    else{
        this.actor().changeClass($dataArmors[itemHolder].meta.c, true);
    }

How would I correctly be able to detect that an item was removed without an error? Clearing everything I can easily handle by just changing class to default in the function.
what is the error?

Actually, you are grabbing the id in equip slot 5, before checking to see if there is anything in that slot. If there's nothing equipped in that slot, that'll throw an error, because there's no object to get the id from. Try moving the var itemHolder line into the else block and see if it makes a difference.

In fact, you're doing things a bit backwards. You're getting the equipment item in slot 5, then getting the id from that item. Later you look up the item based on the id. Why not just use the item you already have, and ditch the id, because it's the item you're interested in?

I've rewritten it below, so it only calls the this.actor() and actor.equips() functions once instead of several times (more efficient), and hopefully it's easy enough for you to follow. I'm not sure how you've got things set up, so I'm going to assume [5] and .meta.c are correct.

Code:
var actor = this.actor();
var equip5 = actor.equips()[5];

if (equip5) { // something is equipped in armor slot 5
  actor.changeClass(equip5.meta.c, true);
} else { // nothing equipped there
  actor.changeClass(5, true);
}


If it still doesn't work, show a screenshot from the console so we can see what it's objecting to.

What is the context? Is this in a plugin you're writing, or is it a script call? What is this? Is this.actor() always going to return an actor object? Could it be null? That could cause further issues.
You solved my problem alright and I understand what you mean about me going about it a bit backwards. I'm not really sure why I wrote it the way I did as it was a couple months ago.

This is a part of a plug in I wrote which changes "Scene_Equip.prototype.onItemOk = function()" to make it so armor slot 5 can be used to change classes for the characters based on what I have in the note section of the item they have equipped.

Every error I was encountering seems to be fixed thank you so much.

Original thread: https://forums.rpgmakerweb.com/threads/removing-an-item-causes-an-error.84781/