w3resource

JavaScript: Create a variable using a user-defined name

JavaScript Basic: Exercise-13 with Solution

Create Variable with User-Defined Name

Write a JavaScript exercise to create a variable using a user-defined name.

This JavaScript exercise involves creating a variable with a name provided by the user dynamically during runtime. It typically utilizes the eval() function or the object bracket notation window[name] to achieve this dynamic variable creation based on user input. However, it's important to handle user input securely to prevent code injection vulnerabilities.

Sample Solution:

JavaScript Code:

// Declare a variable named var_name and assign it the string 'abcd'
var var_name = 'abcd';

// Declare a variable named n and assign it the number 120
var n = 120;

// Assign the value of n to the property named 'abcd' of the 'this' object
this[var_name] = n;

// Log the value of the property 'abcd' of the 'this' object to the console
console.log(this[var_name]); 

Output:

120

Live Demo:

See the Pen javascript-object-exercise-13 by w3resource (@w3resource) on CodePen.


ES6 Version:

// Declare a constant variable named var_name and assign it the string 'abcd'
const var_name = 'abcd';

// Declare a constant variable named n and assign it the number 120
const n = 120;

// Assign the value of n to the property named 'abcd' of the 'this' object
this[var_name] = n;

// Log the value of the property 'abcd' of the 'this' object to the console
console.log(this[var_name]);

Improve this sample solution and post your code through Disqus.

Previous: JavaScript program to get the website URL (loading page).
Next: JavaScript exercise to get the extension of a filename.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-basic-exercise-13.php