How to define optional parameters in Java Script-Collection of common programming errors
Here is my object construction,
function Employee(name, dob) {
this.Name = name;
this.DateOfBirth = new Date(dob);
}
Now, I have created an instance for this, like
var emp = new Employee("sample","12/12/12");
Its working fine when i print the output.
But, if i create the object like
var emp = new Employee(name = "sample");
or
var emp = new Employee(dob = "12/12/12");
its not working fine. In both the cases, the DateOfBirth
field is invalid.
I need to define an object with optional parameters.
-
JavaScript does not support named optional parameters.
When you do
var emp = new Employee(name = "sample");
You’re declaring a
name
global variable, assigningsample
to it and passing that to thenew
call.You can use objects to accomplish similar syntax in JS:
var emp = new Employee({name:"sample"});
Where the Employee function becomes:
function Employee(options) { this.Name = options.name; if(options.dob !== undefined){ this.DateOfBirth = new Date(options.dob); } }
Worth mentioning, in practice, you often don’t need an Employee class, and can simply do:
var emp = {name:"sample"};
Or:
var emp = {dob:new Date("12/12/12");}
So unless Employee grows to become a real model (and has more than just two fields) I think that you might want to consider that.
-
function Employee(params) { if (typeof params != "undefined") { this.Name = (typeof params.name != "undefined") ? params.name : ""; this.DateOfBirth = (typeof params.dob != "undefined") ? new Date(params.dob) : null; } } new Employee({ name: "John", dob: "12/12/12" }); new Employee({ name: "John" }); new Employee({ dob: "12/12/12" });
or using simple statements using
||
.function Employee(params) { params = params || {}; this.Name = params.name || ""; this.DateOfBirth = new Date(params.dob || ""); }
-
As a good practice, you should never leave out variables. You can explicitly call
var emp = new Employee(null, "12/12/12");
This way everything is initialized and you will not havea headaches later on. There is also something like this, but you really need to check the values before assigning.
function Employee() { this.Name = name; this.DateOfBirth = new Date(dob); } var emp = new Employee(name = null,dob = "12/12/12");
Originally posted 2013-11-09 20:19:47.