Making a dynamic variable requires eval
. This is bad practise. There are better alternatives:
Using an object:
var students={};
function addNewStudent(firstName,lastName){
students[firstName+lastName] = new Student(firstName,lastName);
}
addNewStudent('Hero','Man');
students['HeroMan']; // Student instance
students.HeroMan; // Student instance
Using Map
(only supported with ES6):
var students=new Map();
function addNewStudent(firstName,lastName){
students.add(firstName+lastName, new Student(firstName,lastName));
}
addNewStudent('Hero','Man');
students.get('HeroMan'); // Student instance
With the object or the map, you could even get the whole list by accessing students
. Isn’t that much more convenient and sensible?