Table of Contents
In this post, we will see how to get variable name as String in JavaScript.
There are multiple ways to get Get variable name as String in JavaScript. Let’s go through them.
Using Object.keys()
To get variable name as String in JavaScript, use Object.keys()
to get the keys array and get the first element.
1 2 3 4 5 6 7 |
const variableToString = varObj => Object.keys(varObj)[0] const num = 10; const variableNameStr = variableToString({ num }) console.log(variableNameStr); |
Output:
1 2 3 |
num |
Object.keys() returns an array of provided object’s own property names, iterated in same order similar to for loop or while loop.
Using toString() method
To get variable name as String, we can call toString()
method and get variable name from it using replace()
method to remove unwanted part of the String.
1 2 3 4 |
const nameOf = (f) => (f).toString().replace(/[ |\(\)=>]/g,''); console.log(nameOf(() => num)); |
Output:
1 2 3 |
num |
The replace()
method returns a new string with matches of pattern replaced by a replacement string.
It takes 2 parameters.
- Regular expression which we want to match in String.
- Replacement String – String with which we want to replace matched string.
Using hash table
You can use map in these kind of scenarios where you want to map name to some value.
Here is simple example:
1 2 3 4 5 6 |
var obj = { country: 'India' }; obj.population = 10000; for(key in obj) console.log(key + ': ' + obj[key]); |
Output:
1 2 3 4 |
country: India population: 10000 |
That’s all about how to get variable name as String in JavaScript.