1

How to append var value to another var

var price11 = 100;
var i = 11;
var displayprice;
displayprice= price + 'i'; // should assign 100(value of price11) to displayprice.

Is it possible?

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
mkawa
  • 203
  • 2
  • 9

2 Answers2

1

Use eval() ( But I will not prefer this method , you can find out the reason here : Why is using the JavaScript eval function a bad idea? )

var price11 = 100;
var i = 11;
var displayprice;
displayprice = eval('price' + i);

console.log(displayprice);

If it's in global context then get it from window object

var price11 = 100;
var i = 11;
var displayprice;
displayprice = window['price' + i];

console.log(displayprice);

UPDATE : A better way is to use an object instead. Define the object property as your dynamic variable name. You can get the object property value by Bracket notation.

// defining object
var obj = {
  price11: 100;
}
var i = 11;
// retrieve object property 
var displayprice = obj['price' + i];

console.log(displayprice);
Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 1
    While this answer *works* and does what you asked, this is the _wrong_ approach to the issue. As others mentioned, use an object and access it through `[]` properties. `eval` is almost always the wrong answer to any problem. – Jeremy J Starcher May 11 '16 at 17:17
0
  • Never use eval(). Object-Oriented JavaScript - Second Edition: eval() can be useful sometimes, but should be avoided if there are other options. Most of the time there are alternatives, and in most cases the alternatives are more elegant and easier to write and maintain. "Eval is evil" is a mantra you can often hear from seasoned JavaScript programmers. The drawbacks of using eval() are:
    - Security – JavaScript is powerful, which also means it can cause damage. If you don't trust the source of the input you pass to eval(), just don't use it.
    - Performance – It's slower to evaluate "live" code than to have the code directly in the script.
  • Use single var. Object-Oriented JavaScript - Second Edition: Consider a "single var" pattern. Define all variables needed in your function at the very top of the function so you have a single place to look for variables and hopefully prevent accidental globals.
  • Use object properties for dynamic names
var 
  obj,
  i = 11,
  displayprice;

obj.price11 = 100;

displayprice = obj['price' + i]; 

You can get objects's property dynamically: obj['price' + i] => obj['price11'] => 100

Ali Mamedov
  • 5,116
  • 3
  • 33
  • 47