Reputation: 47
Why is it necessary to create and use an empty object at the beginning of the function(like employees in this case). Is there any other way to write this object in this function. This is probably a stupid question but I'm a newbie in javascript.
function allemployees (Firstname,Lastname,Gender,Designation) {
var employee = {};
employee.Firstname = Firstname;
employee.Lastname = Lastname;
employee.Gender = Gender;
employee.Designation = Designation;
return employee;
}
var emp = allemployees("John", "Miller", "M", "abc");
Upvotes: 1
Views: 79
Reputation: 318
First of all there is an error in your code. You declared and initialized employees variable and trying to assign value to emp variable which is not yet declared and thus undefined error.
Try this one
function allemployees (Firstname,Lastname,Gender,Designation) { return {"Firstname":Firstname, "Lastname":Lastname, "Gender": Gender, "Designation": Designation}; }
This will work for you without declaring any variable and will return what you want.
Also what I am getting from you comments is that you have employees data from some where else and want to store that data in javascript object. So you declare and initialized employees variable at the calling point of function allemployees(....).
var employees = {}; employees.push(allemployees("John", "Miller", "M", "abc"));
Upvotes: -1
Reputation: 45121
If I understand your question correctly. You could just return object literal w/o creating a temporary variable.
function allemployees (Firstname,Lastname,Gender,Designation) {
return {
Firstname: Firstname,
Lastname: Lastname,
Gender: Gender,
Designation: Designation
};
}
console.log(allemployees("John", "Miller", "M", "abc"))
Or with ES2015 enhanced object literals the syntax is even shorter.
function allemployees (Firstname, Lastname, Gender, Designation) {
return { Firstname, Lastname, Gender, Designation };
}
console.log(allemployees("John", "Miller", "M", "abc"))
Upvotes: 1