I have a function that takes multiple optional arguments. Currently the function isn't assigning default values in the manner I expect.
var test1 = function(arg1, arg2, arg3, arg4) {
arg1 = arg1 || "arg1";
arg2 = arg2 || "arg2";
var obj = {
arg1: arg1,
arg2: arg2,
arg3: arg3,
arg4: arg4
};
return(obj);
};
var obj1 = test1(arg3 = "notarg1", arg4 = "notarg2"); // Why are these values assigned to arg1 & arg2 instead of 3 & 4?
console.log(obj1);
I don't understand this. Javascript seems to ignore my (arg3 = "notarg1", arg4 = "notarg2")
assignments and instead behaves as though (arg1 = "notarg1", arg2 = "notarg2", arg3 = undefined, arg4 = undefined)
was my input.
var test2 = function(arg1, arg2, arg3, arg4) {
if (arg1 === null) {
arg1 = "arg1";
}
if (arg2 === null || arg2 === "undefined") {
arg2 = "arg2";
}
var obj = {
arg1: arg1,
arg2: arg2,
arg3: arg3,
arg4: arg4
};
return(obj);
};
var obj2 = test2(arg3 = "notarg1", arg4 = "notarg2")
console.log(obj2);
I'm not sure if this is worth including. The situation doesn't change.