Hello it is possible to access the value of a JavaScript variable by name? Example:
var MyVariable = "Value of variable";
function readValue(name) {
....
}
alert(readValue("MyVariable"));
Is this possible, so that the output is "Value of variable"? If yes, how do I write this function?
Thanks
Use bracket notation to get an object's value by a variable key, e.g. obj[myVar] . The variable or expression in the brackets gets evaluated, so if a key with the computed name exists, you will get the corresponding value back.
var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped. Variable declared by let cannot be redeclared and must be declared before use whereas variables declared with var keyword are hoisted.
let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.
Global variables are defined on the window
object, so you can use:
var MyVariable = "Value of variable";
alert(window["MyVariable"]);
Yes, you can do it like this:
var MyVariable = "Value of variable";
alert(window["MyVariable"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With