0

My problem is simple:

I want to concatenate a dynamic variable name in a function, so with the name insert in parameter, when I call the function, she concat automatically the string in the new variable name.

Exemple (wrong, I think):

function blockDL(insertName){

    return var 'block' + insertName + 'DT'= document.createElement('dt');  

};

blockDL('First'); 

I expect the code return:

blockFirstDT = document.createElement('dt');

Thanks for your help ! =)

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
Kys3r
  • 223
  • 3
  • 6
  • 1
    Why would you want to do that? Besides not being possible, I don't see a benefit doing that. You *could* use an object and store the values as properties of the object, but that seems unnecessary for your use case. – Felix Kling May 22 '17 at 15:13

2 Answers2

0

What you want is not possible. See "Variable" variables in Javascript? for alternatives of what you can do.

However, "variable variables" is usually a indicator of bad code design. Especially in your case, there is absolutely no reason or benefit to do any of these. Just name the variables blockDT and paraphDT or whatever you want.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • I need to do this because i dont want repeat the same code for print same block, but i need to change the name of variable inside the function(it's in french): https://openclassrooms.com/courses/dynamisez-vos-sites-web-avec-javascript/manipuler-le-code-html-partie-2-2#/id/r-1924713 – Kys3r May 22 '17 at 15:19
  • No reason to practice with bad practices – juvian May 22 '17 at 15:20
  • @Kys3r: That's all fair and square, but if something is impossible then there is not much you can do about it. *"i dont want repeat the same code"* That's what functions are for. You define a function once and call it as often as you want. The variable names inside the function are basically irrelevant. – Felix Kling May 22 '17 at 15:22
0

The only way you will be able to use a string for a variable name is by placing it as the property of another object. if you want the variable global you could use the window object.

window['block' + insertName + 'DT'] = document.createElement('dt');

that said, you really shouldn't need to and should probably look for other ways of structuring your code.

dgeare
  • 2,618
  • 5
  • 18
  • 28
  • Thanks @dgeare, and now can i use the blockFirstDT outside of the function ? – Kys3r May 22 '17 at 15:40
  • @Kys3r anything defined on the window object will be a global property. so you could access it the same way from anywhere in your application. window.blockFirstDT and window["blockFirstDT"] are both proper ways of accessing the value. – dgeare May 23 '17 at 14:40