Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Convert a Map to JSON String in JavaScript ?
Next article icon

How to Convert String to Variable Name in JavaScript?

Last Updated : 27 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, if we consider the variable names as string values, it is difficult to transform a variable’s name into a string. However, this problem has been handled in many ways for example, static properties of objects, eval(), and modern ways such as Map can be used to achieve the essential effect of dynamic variable creation, such methods are appropriate for managing dynamic variables.

These are the following approaches to convert a string to a variable name.

Table of Content

  • Using Object Properties
  • Using the eval() Function (Not Recommended)
  • Using Map or WeakMap (Modern Approach)

Using Object Properties

A JavaScript object is a collection of key-value pairs. Where the key is a string or symbol, you can dynamically assign properties to objects using strings as keys, this method is one of the simplest and most used techniques for simulating the conversion of strings to variable names, this works because objects can access properties and is defined using parentheses that accept strings as keys.

Syntax:

const obj = {};
obj['dynamicKey'] = value;

Example: In this example, We create an empty object obj and dynamically add properties using strings stored in key variables, the username property of the object is created and set to 'Pankaj Kumar Bind', which allows for flexible handling without having to hardcode dynamic attribute names.

JavaScript
const obj = {}; const key = 'username'; obj[key] = 'Pankaj Kumar Bind';  console.log(obj.username);  

Output
Pankaj Kumar Bind 

Using the eval() Function (Not Recommended)

The eval() function allows you to execute JavaScript code that is expressed as a string although this method can be used to convert strings to variable names by dynamically creating and executing code however it is not strongly recommended, using eval() can lead to severe security vulnerabilities, this is especially true when dealing with user-generated input, it can also negatively impact performance, this forces JavaScript engine to compile new code on the fly.

Syntax:

eval('var ' + variableName + ' = value;');

Example: In the given below example eval() takes a string that forms a JavaScript variable declaration and assigns it a 'dynamic value', although this achieves its goal, using eval() introduces security risks, such as the possibility of running code that dangerous therefore it is generally recommended to avoid this method.

JavaScript
const variableName = 'myVar'; eval('var ' + variableName + ' = "Dynamic Value";');  console.log(myVar); 

Output
Dynamic Value 

Using Map or WeakMap (Modern Approach)

The map is an interface provided by JavaScript programming language to implement collections of ordered key-value pairs unlike objects where keys are limited to strings or symbols in Map, the keys can be of any data type and this means that Map can perform better than plain old objects at storing dynamic keys and it also provides useful methods like set(), get(), has(), etc thus making it a good approach to deal with such dynamic variable name.

Syntax:

const map = new Map();
map.set(key, value);

Example: In the given below example Map object is used to store dynamic key-value pairs, the string 'age' is set to the key, and the number 25 is stored as its value, unlike simple objects, Map allows more complex key types and has built-in methods for manipulating items, this makes it ideal for dynamic key assignments.

JavaScript
const map = new Map(); const dynamicKey = 'age'; map.set(dynamicKey, 20);  console.log(map.get('age'));  

Output
20 

Next Article
How to Convert a Map to JSON String in JavaScript ?
author
pankajbind
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

  • How to Convert String to JSON in JavaScript?
    In JavaScript, converting a string to JSON is important for handling data interchangeably between server and client, parsing external API responses, and storing structured data in applications. Below are the approaches to converting string to JSON in JavaScript: Table of Content Using JSON.parse()Us
    2 min read
  • How to Convert JSON to string in JavaScript ?
    In this article, we are going to learn the conversion of JSON to string in JavaScript. Converting JSON to a string in JavaScript means serializing a JavaScript object or data structure represented in JSON format into a textual JSON string for data storage or transmission. Several methods can be used
    3 min read
  • How to Convert a Map to JSON String in JavaScript ?
    A Map is a collection of key-value pairs, where each key is unique. In this article, we will see how to convert a Map to a JSON (JavaScript Object Notation) string in JavaScript. However, JSON.stringify() does not directly support Map objects. Table of Content Using Object.fromEntries() MethodUsing
    2 min read
  • How to Create a String with Variables in JavaScript?
    To create a string with variables in JavaScript, you can use several methods, including string concatenation, template literals, and the String methods. Here are the common approaches: 1. Template Literals (Recommended)Template literals are the modern and most preferred way to create strings with va
    2 min read
  • How to Use Dynamic Variable Names in JavaScript?
    Dynamic variable names are variable names that are not predefined but are generated dynamically during the execution of a program. This means the name of a variable can be determined at runtime, rather than being explicitly written in the code. Here are different ways to use dynamic variables in Jav
    2 min read
  • How to convert an object to string using JavaScript ?
    To convert an object to string using JavaScript we can use the available methods like string constructor, concatenation operator etc. Let's first create a JavaScript object. [GFGTABS] JavaScript // Input object let obj_to_str = { name: "GeeksForGeeks", city: "Noida", contact: 248
    4 min read
  • How to Convert String of Objects to Array in JavaScript ?
    This article will show you how to convert a string of objects to an array in JavaScript. You have a string representing objects, and you need to convert it into an actual array of objects for further processing. This is a common scenario when dealing with JSON data received from a server or stored i
    4 min read
  • How to Convert String to Camel Case in JavaScript?
    We will be given a string and we have to convert it into the camel case. In this case, the first character of the string is converted into lowercase, and other characters after space will be converted into uppercase characters. These camel case strings are used in creating a variable that has meanin
    4 min read
  • What are the variable naming conventions in JavaScript ?
    When we name variables in javascript, we've to follow certain rules. Each variable should have a name that appropriately identifies it. Your JavaScript code gets easier to comprehend and work with when you use suitable variable names. It's critical to name variables correctly. For example Constants
    2 min read
  • Convert a Number to a String in JavaScript
    These are the following ways to Convert a number to a string in JavaScript: 1. Using toString() Method (Efficient and Simple Method)This method belongs to the Number.Prototype object. It takes an integer or a floating-point number and converts it into a string type. [GFGTABS] JavaScript let a = 20;
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences