skip to Main Content

I am very new to javascript and I was making a rock, paper, scissor game, but the below lines of code is giving me undefined value can someone explain me in simple words why console log is giving me undefined as output .

let userval = prompt("enter R,P,S");
const object={
  R : "ROCK",
  P : "PAPER",
  S : "SCISSOR"
};
console.log(object.userval)

I want the console to log "ROCK" when i enter R in prompt and so on.

2

Answers


  1. It looks like you are trying to reference userval as a property on the object that you defined, when really you want to be using the value to look up a property.

    Perhaps try console.log(object[userval])?

    It is helpful to set debug breakpoints in the dev tools to examine how objects are constructed as well, and to experiment with different calls in the console.

    Login or Signup to reply.
  2. object.userval is equivalent to object['userval']. You need to use object[userval] in order to access the userval variable.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search