-3

I want to create new variable from these function parameter. How can it be done?

function addNewStudent(firstName,lastName){
var firstName+lastName = new Student();
}

addNewStudent('Hero','Man');

Error Msg: Uncaught SyntaxError: Unexpected token +

  • 1
    Doing this with an array or an object literal (or `Map` or `Set`) would be much easier. While it’s more or less possible with a variable (using `eval`), it’s bad practice. – Sebastian Simon Sep 06 '15 at 18:57
  • Looks like you need something like this `new Student(firstName, lastName)` instead. – dfsq Sep 06 '15 at 18:58
  • What exactly are you trying to accomplish here? The attempt doesn't make a lot of sense to me. – David Sep 06 '15 at 18:58
  • 2
    possible duplicate of [Use dynamic variable names in JavaScript](http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript) – JJJ Sep 06 '15 at 19:00

2 Answers2

0

I would recommend a solution as suggested by @dfsq above:

function Student(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

var student1 = new Student('Jane', 'Doe');
var student2 = new Student('John', 'Smith');

console.log(student1.firstName, student1.lastName);
console.log(student2.firstName, student2.lastName);

http://jsfiddle.net/8m7351fq/

But if you must do it the way that you specify above:

var students = {};

function addNewStudent(firstName,lastName){
    students[firstName+lastName] = 'Some random data';
}

addNewStudent('Hero','Man');
console.log(students);

http://jsfiddle.net/em1ngm2t/1/

grgdne
  • 241
  • 1
  • 7
0

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?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75