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
It looks like you are trying to reference
userval
as a property on theobject
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.
object.userval
is equivalent toobject['userval']
. You need to useobject[userval]
in order to access theuserval
variable.