Home > OS >  Can we simplified this code? show = typeof show == 'undefined' ? undefined : !show
Can we simplified this code? show = typeof show == 'undefined' ? undefined : !show

Time:09-23

function myToggle(show) {
    //...bunch of codes here...

    show = typeof show == 'undefined' ? undefined : !show
    $(el).toggleClass('d-none', show )
}

In above function, show will be inverted (boolean) only if its defined, then pass into jQuery's toggleClass(). d-none is a Bootstrap class to hide element.

So that when:

myToggle()    //this will toggle class d-none to the element
myToggle(1)   //this will remove class d-none from the element
myToggle(0)   //this will give class d-none to the element

So my question, can we simplified this code?

show = typeof show == 'undefined' ? undefined : !show

CodePudding user response:

Let's start with the fact that this should be ===, not just ==. You almost never want == in JS (it's not Java or C , always use === unless you actually know why you shouldn't). With that, you don't need a typeof check: just check whether your var is undefined, directly.

show = show === undefined? show : !show;

However, this ignores how jQuery's .toggleClass() even works. It doesn't take "true or false or undefined" as second argument, it takes a boolean, and "show" is pretty explicit in its intention, so the real simplication is the most obvious one:

show = !!show;
  • Related