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.
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
// 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.
Hi there, I’m Rodney.
Writer, Game Designer, Editor, Kitbasher, Skateboarder, and Ork ‘Ed Banga. But Nothing Without Christ!