0

I am having a problem accessing a global variable in a key event. When I use name it prints undefined, but if i use anotherVariableName it works. Does anyone know why? The following code is done in javascript.

var name = {
    "key": "value"
}

document.onkeyup = function (event) {
    console.log("name is", name["key"])
}

https://i.stack.imgur.com/YtbHZ.png

Tân
  • 1
  • 15
  • 56
  • 102
abm
  • 1
  • 1
  • 3

4 Answers4

0

Please try below code. It's working.

const name = {
    "key": "value"
}

document.onkeyup = function (event) {
    console.log("name is", name.key)
}
Mukesh Singh Thakur
  • 1,335
  • 2
  • 10
  • 23
0

You are shadowing the name property on the window object. You can use ES6 syntax (let or const) or you can use another variable name.

ruby_newbie
  • 3,190
  • 3
  • 18
  • 29
0

The global window object has already a name property which is the name of the current window. Hence when you use name it returns the name of the window which is of type string. so when you do name["key"] it is checking for property key in a string which is undefined all the time.

You can either use a different variable name or you can use ES6 let or const to declare your variable.

Santosh
  • 2,093
  • 1
  • 15
  • 21
0

As MDN page says,

The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global. If you re-declare a JavaScript variable, it will not lose its value.

In this case, name is global and it points already existing variable, window.name.

Also, according to Window.name page,

window.name will convert all values to their string representations by using the toString method.

So value of name is "[object Object]" that is String. You can check this by

var name = {"key":"value"};
console.log(name); // [object Object]

key property of String value "[object Object]" is undefined, this is why you get undefined.

yk125
  • 361
  • 3
  • 7