Explain Codes LogoExplain Codes Logo

Use dynamic variable names in JavaScript

javascript
dynamic-variables
javascript-patterns
best-practices
Anton ShumikhinbyAnton Shumikhin·Jan 5, 2025
TLDR

Harness objects as a key-value repository in JavaScript to construct dynamic variable names. Select bracket notation to access properties with variable keys. Exemplified below.

let kvStore = {}; // Key-value storage let propName = "dynamicName"; // Your dynamic variable kvStore[propName] = "value"; // Assigning the value console.log(kvStore.dynamicName); // Outputs 'value'

The kvStore[propName] sets or retrieves a property with the name held in propName, making dynamic naming not just possible but also manageable within an object structure.

Function context and dynamic variables

Context-specific variables using this

Use constructor functions or class syntax combined with the new keyword to create multiple instances, each containing a set of dynamic variables:

function MagicBox() { this.reveal = function(spell) { this[spell] = 'Now for the magic trick! Abracadabra!'; // Post magical incantation return this[spell]; }; } let myBox = new MagicBox(); console.log(myBox.reveal('rabbit')); // Outputs 'Now for the magic trick! Abracadabra!'

Such encapsulation of dynamic properties within each instance prevents the pollution of the global scope.

Creating dynamic global variables

In a browser environment, the global window object is available; use it to manipulate global variables dynamically:

let globalVarName = 'dynamicGlobal'; // Name selector window[globalVarName] = 'Global test'; // Assigning global value console.log(window.dynamicGlobal); // Outputs 'Global test'

Why avoid eval()

While eval() allows creating dynamic variables, it also introduces both security risks and performance hits, hence it's advisable to stick to objects and their inherent dynamic key-value storage capability.

Handling dynamic data

Mass Creation of dynamic variables

Use a loop to create more dynamic variables at once:

for(let i = 0; i < 5; i++) { // It's like 'prop0' to 'prop4' are graduating from Hogwarts! kvStore['prop' + i] = 'value' + i; }

Using template literals for property names

Since ES6, we've had the chance to witness the elegance of creating property names with template literals:

let index = 5; kvStore[`prop${index}`] = 'Five'; // That's 'prop5' for the Muggles console.log(kvStore.prop5); // Outputs 'Five'

Nifty tricks with Proxy

Apply the Proxy object to create a wrapper for another object, intercepting default operations such as property lookup and assignment, function invocation, and others:

const dynamicProxy = new Proxy({}, { get(target, prop) { if(!(prop in target)) { // If prop doesn't exist // Prop now exists, and it's a master of comeback lines! target[prop] = `Dynamic value for ${prop}`; } return target[prop]; } }); console.log(dynamicProxy.unknownProp); // Outputs 'Dynamic value for unknownProp'

Points of attention

Scope considerations

Be wary of variables leaking into the global scope due to function scope peculiarities in JavaScript. Prevent unexpected behavior - declare your variables with var, let, or const.

Refactoring and readability concerns

Dynamic variable names risk making code more complex to refactor and less readable. Make sure to annotate your intentions clearly and to utilize this functionality judiciously.

Influence on performance

While handy, these dynamic patterns can cause performance degradation if used improperly or excessively, especially in a global context. Hence, always use and test these patterns thoughtfully.