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]);

For more Practice: Solve these Related Problems:

  • Write a JavaScript program that prompts the user for a variable name and value, then creates the variable dynamically.
  • Write a JavaScript program that stores user-defined variable names and corresponding values in an object.
  • Write a JavaScript program that creates a variable using a user-specified name via eval() and then logs its value.

Go to:


PREV : Get Current Website URL.
NEXT : Get File Extension of Filename.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.