Reputation: 1076
I did some research but I didn't find a satisfying answer yet. I have a javascript project file and a library where some functions are defined like this:
//Library.js
FElib = {
initLib: function(param1, param2){
var init = param1 || true;
console.log(init);
}
}
Now in my project.js file I call the function and pass false as a parameter
FElib.initLib(false, 'test');
In this case param1 is giving me 'false' if I log it before the variable declaration. Afterwards it's using the default 'true'. It seems like it is interpreting false as undefined were I thought that it's only checking for undefined..
Why is the behaviour like this?
When I'm using a string it's perfectly working. Using 0 or 1 as a parameter is also not working and it's using the default variable declaration..
As a workaround I declared the variable as an object which is workin fine again like so:
//Library.js
FElib = {
initLib: function(options){
var defaults = {
param1: true,
param2: 'string',
};
var options = $.extend({}, defaults, options);
}
}
Now calling the function is working fine even with boolean arguments:
FElib.initLib({'param1':false, 'param2':'string123'});
The 2nd approach seems to have a little overhead thinking of a function with only 1 boolean variable as an argument.
Can anybody explain this behaviour?
Upvotes: 3
Views: 9532
Reputation: 72857
The problem is here:
var init = param1 || true;
The boolean OR
operator (||
) returns true
there, since it's evaluating: false || true
;
"False or True" is always "True".
If you want to check if the parameter is undefined, use something like this:
var init = (typeof param1 === "undefined") ? true : param1;
Upvotes: 4
Reputation: 324650
UH... because init = param1 || true
isn't checking for undefinedness, it's checking for falsiness.
false is, obviously, falsy, and it is therefore replaced with true.
If you want to check for undefinedness, there is no real shorthand to it:
var init = typeof param1 === "undefined" ? true : param1;
Upvotes: 11
Reputation: 943569
Because the ||
operator is testing for truthyness, not definedness.
You will get the right hand side of the ||
operator if the left hand side evaluates as false, which false
does.
If you want to test if a value is defined use:
var init = param1;
if (typeof param1 === "undefined") {
init = true;
}
or
var init = (typeof param1 === "undefined") ? true : param1;
Upvotes: 3