sqerl
sqerl

Reputation: 11

Can't understand why this is showing as undefined

I'm starting to build a simple text adventure game, and can't figure this issue out at all. I type 'inspect table' into the text box. Inspect is stripped out, leaving only table, which is then passed to the inspect function. When I try to change innerHTML to input.description I get undefined. Yet when I use table.description it works fine.

const text = document.querySelector('#text');
const userForm = document.querySelector('#user-form');
let userInput = document.querySelector('#user-input');

const table = {
  description: 'Plates and silverware are on the table',
  items: ['plates', 'silverware'],
  itemDescrips: ['rotting food sits on the plates.', 'just silverware']
};  

let inspect = function(input) {
  //Returns undefined
  text.innerHTML = input.description;

  //Oddly, this works fine
  //text.innerHTML = table.description
};

userInput.addEventListener('keydown', (e) => {
 
  if (e.keyCode == 13) {
    let command = userInput.value.split(' ');
    if (command.includes('inspect')) {
      //I've checked the type of this argument and it is a string.
      inspect(command[1]);
    }
    userForm.reset();**strong text**
    e.preventDefault();
  } 

});

Upvotes: 0

Views: 79

Answers (2)

sqerl
sqerl

Reputation: 11

You guys got me thinking, and helped me realize i could use conditional logic in the inspect function to make this work.

let inspect = function(input) {
 if (input == 'table') {
   text.innerHTML = table.description;
 }
};

Upvotes: 1

Zé Carlos
Zé Carlos

Reputation: 1

You're passing a simple text to your inspect function and this text doesn't have a property called description. That's why you're getting an undefined return.

Assiging just the parameter input to your text.innerHTML works fine.

let inspect = function(input) {
  text.innerHTML = input;
};

Upvotes: 0

Related Questions