Reputation: 1205
I have a function in my script.js similar to:
function test(var1,var2=0,var3=0) {
// js
}
The function works fine, but when testing it in chrome it returns as undefined. I have tested it around and found that the reason chrome does not accept this function is due to var2=0,var3=0. I tried var2=false,var3=false, but still the same result.
These variables are needed, but not always called, so what would be the solution in this case, as chrome apparently does not like variables being declared like that ?
Thanks
Upvotes: 1
Views: 179
Reputation: 405
It's easy, you can't define variable in function declaration, but you can check this variables after functions invocation. If second or third arguments don't pass to function, then after invocation, this arguments will be undefined, and if arguments is undefined, then result of expression var || 0, will be 0.
function test(var1,var2,var3) {
var2 = var2 || 0;
var3 = var3 || 0;
// js
}
Upvotes: 2
Reputation: 2606
but when testing it in chrome it returns as undefined
yes it does, because the function has no return value
also, default parameter cannot defined like this: test(var1,var2=0,var3=0)
Silver_Clash's solution works:
function f(opt){
opt = opt||"default"
console.log(opt);
return opt;
}
f("hello");
f();
//output:
//hello
//default
Upvotes: 0