w3resource

JavaScript: Create a variable using a user-defined name

JavaScript Basic: Exercise-13 with Solution

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

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

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

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.



Follow us on Facebook and Twitter for latest update.