Game Dev For Busy Overlords Banner

Convert a String to a Variable Name in JavaScript

Is it possible to write code that doesn’t use its own variables, but still works? It is! You can convert a string to a variable name in JavaScript using eval, and here’s how it works.

Convert a string to a variable name

Our Usecase

Say we’re building a text-based game where we want the player to be able to interact with the resources they’ve collected. In Mars and Crafts, this means typing “atomize [resource name]” into Discord and hitting enter. For example: “atomize dirt” or “atomize concrete”.

There are potentially many variables we’ll need to access, but the user is giving us the name of the most important variable in their input string. So, rather than using many “if-else” statements, can’t we just use the input string to get the variable?

Convert a JS String into a Variable Name

This node.js code loads data from a JSON file into variables, then uses eval to access them with a string. This is useful because the user can type in the variable’s name and get its value, all we need to do is ensure their string is formatted correctly.
// Load Game
const fileSystem = require("fs");
const saveData = fileSystem.readFileSync("saveData.json", "utf-8");
const saveObj = JSON.parse(saveData);
console.log("Loaded save game.......");

//Resources
var iStone = saveObj.iStone;
var iWater = saveObj.iWater;
var iSludge = saveObj.iSludge;
var iParts = saveObj.iParts;
var iElectronics = saveObj.iElectronics;
var iFuel = saveObj.iFuel;
var iPower = saveObj.iPower;
var iMetal = saveObj.iMetal;
var iConcrete = saveObj.iConcrete;
var iDirt = saveObj.iDirt;

function atomize (arg) {
    // Convert arg string to resource variable name
    arg = arg.toLowerCase();
    var sResPrefix = "i" + arg.charAt(0).toUpperCase(); 
    var sResource =  sResPrefix + arg.substr(1, arg.length);
    console.log(arg + " => " + sResource + " = " + eval(sResource)); 
}

// Some tests
atomize ("dirt");
atomize ("Water");
atomize ("CONCRETE");
atomize ("Stone");
atomize ("sludge");
atomize ("FUEL");

We can figure out which variable the user wants with some educated guesses. In this case, we know our variables all start with “i” and a capital letter. We then do a fair bit of work with the strings, which we could skip if the variable names were simply the nouns (“sludge”, “water”, “stone”, etc.).

Here’s the saveData.json file:

{
"iStone":3,
"iDirt":2,
"iWater":0,
"iSludge":0,
"iParts":0,
"iElectronics":0,
"iFuel":0,
"iPower":0,
"iMetal":0,
"iConcrete":0
}

Some Security Considerations

Using eval is like opening a back door for all kinds of deviancy, which is why you’ll still need to restrict which variables are accessible and ensure that only those variables are accessible. Read and understand the eval docs, and let us know if you have a better way of doing this, in the comments below.



Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.