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:
Output:
120
Live Demo:
ES6 Version:
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.