See if variables exist without equal signs in an if statement (can it be done?)

Viewed 46

I have a question about best practices and if it is possible or if it can/should be done this way to eliminate some "unnecessary" code. Can I create an if statement like this? I mean, at least it works for me, but is it normal?

var ModeloA = true, 
    ModeloB = false;
        
if (ModeloA) {
    console.log("example");
}
if (!ModeloB) {
    console.log("example");
}

Instead of:

if (ModeloA === true) {
        console.log("example");
}
if (ModeloB !== true) {
        console.log("example");
}

And in this case, can I do the same?

 var ModeloC = document.querySelector("[class*=ModeloC]");
    if (ModeloC) {
            console.log("example");
    }

Instead of:

 var ModeloC = document.querySelector("[class*=ModeloC]");
        if (ModeloC !== null) {
                console.log("example");
        }

Also, I just want to say that my javascript is not excellent, I learned it myself to automate some things that make my life easier (and I'm still learning). If anyone can help me, I'd be very grateful.

1 Answers

Since this is a question of code style and therefore in a way a question of preference, there isn't a single correct answer. There are however some problems with the syntax you are using that you ought to be aware of.

If the type of the variable you are checking is boolean, then I would spare the === true. Since all this does is create another boolean value and compare that. So essentially the code is useless and when you name your boolean variables properly, the if statement remains very readable without the extra code. This is however a question of preference.

However: If the type of the variable you are checking is non-boolean. I would recommend always using strict checking (e.g. variable === undefined || variable === null). Since JavaScript sometimes shows very peculiar behaviour with types - especially for people who are used to strictly typed languages, there are many scenarios in which omitting the === 'somevalue' can be misleading.

For example: !0 or !'' will all result in false. Which when checking for null or undefined might break your code.

Related