Returning a variable name instead of its value

As an experiment with string literal templates, I was trying to insert the variable’s name into the template, not the value. Is this possible?
My code:

let testArr = [1, 2, 3, 4];
let arrAssess = (x) => {
let a = x.length;
return `$[x] Is an array with $[a] indexes.`;
}

With the code like this, arrAssess(testArr); returns ‘1,2,3,4 is an array with 4 indexes.’
Is there any way to make it return ‘testArr is an array with 4 indexes.’ ?

I do not believe this is possible; variable names are arbitrary as far as the computer is concerned (though they should make sense to human readers). As far as I know, you wanted something like this, you’d have to add some sort of ‘name’ property to an object.

In Python, there is method all objects can implement that provides a way to display the object. That’s the closest thing that comes to mind.

1 Like

The following is about as close as you might get to something like you are wanting:

const testArr = [1, 2, 3, 4];

const convertVariableObjToString = varObj => Object.keys(varObj)[0]

const variableName = convertVariableObjToString({ testArr })
console.log(`${variableName} is an array with ${testArr.length} indexes.`);

The above displays testArr is an array with 4 indexes. to the console.

3 Likes

You could also do something like:

const getArrayVariableInfo = arrVarObj => {
  const name = Object.keys(ArrVarObj)[0];
  const length = arrVarObj[name].length;
  return { name, length };
};

const testArr = [1, 2, 3, 4];
const arrInfo = getArrayVariableInfo({ testArr });
console.log(`${arrInfo.name} is an array with ${arrInfo.length} indexes.`);

OR

const getArrayVariableInfo = arrVarObj => {
  const name = Object.keys(arrVarObj )[0];
  const length = arrVarObj [name].length;
  return `${name} is an array with ${length} indexes.`;
};

const testArr = [1, 2, 3, 4];
console.log(getArrayVariableInfo({ testArr }));

If someone wants to dive deeper into this,
there is an interesting thread about it on stackoverflow.