Proper way to set a function's default parameter to a boolean?

I've a function read() that takes as a boolean paramater. If false is passed in - read(false) - it shouldn't run a block of code. It works with the three variations below, but I'm not sure the difference between them or if it matters?

But I don't understand the difference between the variations.

All these three variations work.

this.first_time_here = first_time_here !== false;
var first_time_here = first_time_here !== false;
var first_time_here = first_time_here || false;

read function

   function read (first_time_here) {

            var first_time_here = first_time_here !== false;

            // check to see what the function thinks first_time_here is
            console.log("first time here is:  " + first_time_here);
            if (typeof first_time_here === 'boolean') {
            console.log('Yes, I am a boolean');
            }

            if (first_time_here) {
                   // do something if true

         };
    };

Thank you

Answers:

Answer

If you're expecting falsey values, use typeof:

var x = typeof x !== 'undefined' ? x : false;

Otherwise, if you do this:

var x = x || true;

And pass in false, the value of x will be true.

Answer

It's because the concept automatic conversion in Javascript, the undefined value convert to false. So three lines are similar to ensure the variable first_time_here is false, not undefined.

if first_time_here is undefined:

first_time_here = undedined !== false -> first_time_here = false != false
-> first_time_here = false;

And:

first_time_here = undedined || false -> first_time_here = false || false
-> first_time_here = false;

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.