Why is a boolean false parameter not interpreted when passing to a function?

javascript, jquery

Solution

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;

Problem

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?

Original source