What is the method to generate a JavaScript variable using a string value?

I need assistance in generating a variable dynamically, where its name corresponds to the value of a specific string. Here’s an example of what I’m trying to achieve:

let username = 'alice';
let content = 'example content';

// ... further operations

console.log(alice); // should display 'example content'

You can achieve this using the window object in the browser environment. Here's a simple solution:

let username = 'alice';
let content = 'example content';

window[username] = content;

console.log(alice); // Output: 'example content'

Note: This approach is only applicable in the global scope of a browser. Avoid using it to prevent variable conflicts.

In a Node.js environment, using a global object like window won't work. However, you can utilize an object to achieve this dynamically:

let username = 'alice';
let content = 'example content';

// Create a dynamic object to store key-value pairs
let dynamicVariables = {};

dynamicVariables[username] = content;

console.log(dynamicVariables['alice']); // Output: 'example content'

This method keeps the code efficient and avoids potential global scope conflicts, especially important in environments outside browsers.