snipt

Ctrl+h for KB shortcuts
Notice: Snipt is moving away from free accounts on May 1st, 2014. Read more about the transition here.
#117144

JavaScript

NodeJS - Variables with dynamic name

1
2
3
4
5
6
7
var varName1 = "varName2"
global[varName1] = "Hello World" // This is the important line ;)
var staticVarName = global[varName1] 

console.log("Var1: Name/Value : varName1/" + varName1)
console.log("Var2: Name/Value : " + varName1 + "/" + global[varName1])
console.log("Static Var: Name/Value : staticVarName/" + staticVarName)
https://snipt.net/embed/d3e133b2e9b73dd4aeb2fc01608eea0e/
https://snipt.net/raw/d3e133b2e9b73dd4aeb2fc01608eea0e/
d3e133b2e9b73dd4aeb2fc01608eea0e
js
JavaScript
7
2014-04-15T08:59:50
True
False
/api/public/snipt/117144/
creating-variables-with-dynamic-name
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><a href="#L-1">1</a> <a href="#L-2">2</a> <a href="#L-3">3</a> <a href="#L-4">4</a> <a href="#L-5">5</a> <a href="#L-6">6</a> <a href="#L-7">7</a></pre></div></td><td class="code"><div class="highlight"><pre><span id="L-1"><a name="L-1"></a><span class="kd">var</span> <span class="nx">varName1</span> <span class="o">=</span> <span class="s2">&quot;varName2&quot;</span> </span><span id="L-2"><a name="L-2"></a><span class="nx">global</span><span class="p">[</span><span class="nx">varName1</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;Hello World&quot;</span> <span class="c1">// This is the important line ;)</span> </span><span id="L-3"><a name="L-3"></a><span class="kd">var</span> <span class="nx">staticVarName</span> <span class="o">=</span> <span class="nx">global</span><span class="p">[</span><span class="nx">varName1</span><span class="p">]</span> </span><span id="L-4"><a name="L-4"></a> </span><span id="L-5"><a name="L-5"></a><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">&quot;Var1: Name/Value : varName1/&quot;</span> <span class="o">+</span> <span class="nx">varName1</span><span class="p">)</span> </span><span id="L-6"><a name="L-6"></a><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">&quot;Var2: Name/Value : &quot;</span> <span class="o">+</span> <span class="nx">varName1</span> <span class="o">+</span> <span class="s2">&quot;/&quot;</span> <span class="o">+</span> <span class="nx">global</span><span class="p">[</span><span class="nx">varName1</span><span class="p">])</span> </span><span id="L-7"><a name="L-7"></a><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">&quot;Static Var: Name/Value : staticVarName/&quot;</span> <span class="o">+</span> <span class="nx">staticVarName</span><span class="p">)</span> </span></pre></div> </td></tr></table>
dynamic, node, variable