Is there a better way to write this mutiple or conditional? - javascript

I have the following IF statement in javascript:
if ( !(cmd === 'JustifyLeft' || cmd === 'JustifyRight' || cmd === 'JustifyCenter' || cmd === 'JustifyFull') )
Any suggestions on how it could be written in a cleaner way?
Thanks

if(!cmd.match(/^Justify(Left|Right|Center|Full)$/))
In response to a few comments you can also mimic your strict comparison with a small edit:
if( typeof cmd != 'String' || !cmd.match(/^Justify(Left|Right|Center|Full)$/))
This will react in the exact same way as your current code, ignoring anything that's not a string.
Personally I think it is highly unlikely that you will need it.

This sounds like a good situation to use a switch. Just be aware that switches only do equality checking (==) not identity checking (===), though this should be fine.
switch (cmd) {
case "JustifyLeft" :
case "JustifyRight" :
case "JustifyCenter" :
case "JustifyFull" :
// do something
break;
case "somethingElse" :
default:
// do something else
break;
}

I would create a IsJustifyCommand(s) method or create a command abstract class that has a IsJustifyCommand() method on it. Then the code will read like a description of what it is trying to do.
Using regex may be neat, but will lead to maintenance problems if someone that is not a hard-core JavaScript programmer has to work on the code. However if you have lots of cases when regex is a good solution, then use it, as anyone looking at the code will soon pick it up.
(However I am a C# programmer not a JavaScript programmer, but like most programmer I have to look at / edit JavaScript code sometimes. I think most JavaScript is maintained by none JavaScript programmers.)

I hate when something is written like that. First I look at the code and think "if cmd is equal to JustifyLeft or JustifyRight... then invert that and... if that's true do the thing.. so that means if it's JustifyLeft...". For me it takes alot of time and I have to re-read the line to be sure I got it right.
I think it's better to write.
if ((cmd !== 'JustifyLeft') && (cmd !== 'JustifyRight') && (cmd !== 'JustifyCenter') && (cmd !== 'JustifyFull'))
It might be a little more verbose but I find it easier to follow. I read it as "cmd can't be any of the Justify-strings". Checking a long boolean expression and then inverting the whole answer is irritating.
I like the solution from scragar, just wanted to give my thoughts about inverting a long boolean expression.

Related

Inline code with and is not working but using the regular if works

I have the following code amd it gives me compilation error:
for(var i in test){
(this.watcherFailureCount> 10) && break
}
However the following works:
if(this.watcherFailureCount> 10)
{
break
}
Am I missing anything here? why the first one is not working for me?
The && tries to evaluate your expression and cast its return value to boolean. The break you use is a keyword that controls the loop and should not be used in expressions.
Some languages allow that but it just seems that js doesn’t. And to be fair it is ok not to because is missleading. Imagine conditions like: a && b && break && c && d = a.
There is no real benefit in the first option unless you codegolf or something, and if you codegolf you chosed the wrong language :).
Dont fully understand what youre trying to achieve here however impretty sure the first code snippet is incorrect syntax.
If you want that as an inline if statement try:
if(this.watcherFailureCount>10)break;
However ensure if you are using break that it is inside of some form of code loop like a while or a for loop. And using && with break is invalid as break cannot be a true or false statement so it cant be used like that.

When does it make sense to use double equality (loose equality) in Javascript?

Given the type coercion and the performance issue, as a JS newbie, I've always tried to avoid using double equality and opted for triple equality instead.
However, when does it make sense to use double quality?
Short answer: it never makes sense to use == instead of ===.
Long answer: while it never makes sense, there are cases where you want to write less code, and you are sure about your input.
== is not that bad if you really understand what's truthy. There are some gotchas, for example [1] == true and [2] == false.
Remember that the principal aim of Javascript was to be an easy language to be used by web designers, that's one of the reasons behind all this stuff you encounter.
As a simple example, as Barmar said, the best approach is to use it to avoid converting data and check equality. Here is another example:
const deleteTodos = _ => {
if (howManyTasksToRemoveInput.value == tasks.length) {
warningLabel.innerHTML = "You can't remove all the list";
} else if (howManyTasksToRemoveInput.value > tasks.length) {
warningLabel.innerHTML = "You DEFINITELY can't remove more tasks than you have";
} else {
tasks.splice(0, +howManyTasksToRemoveInput.value);
}
}
There's one case where there's a clear benefit to using ==, which is foo == null: this is true if and only if foo === undefined || foo === null, a commonly useful test.
Even here, using something like node's isNullOrUndefined(foo) (which is implemented as return value == null;!) is a much clearer way to express the intent, if it's not an established practice in the code-base you're working in.
When you want to allow Javascript to convert types automatically. E.g.
if (someElement.value == 3)
value of an input is always a string. The == operator will automatically convert it to a number here, so you don't have to write
if (parseInt(someElement.value) === 3)
You should be careful, since some some of the automatic conversions may not do what you expect.

javascript leaving an empty if statement

I would like to know if leaving an empty if statement for certain situations as:
else if(typeof console === 'undefined'){}
Just to have the code bypass the rest of the function It is an accepted and safe way to work or there are other recommendation practices for these cases?. Thank you.
It's fine and safe to leave if branches empty, the only thing I would add is a comment:
else if(typeof console === 'undefined')
{
//explanation why nothing has to go here
}
Without seeing the rest of the code I'm unsure how you're using this to "bypass the rest of the function", there may be a better way to do this.
From what information you've provided me, I can glean that the answer is "no". It will work, but it's bad style. If you would like to bypass the rest of the function, why not return; or put most of the logic in the if statement that pertains to it so that there is no bypassing at all?
I just had a case in which I chose to use an empty if-statement (professional context). I must agree though, there definitely is a technically cleaner solution. Still, since in a professional context time is important too, I chose to use the empty if-statement in my case, so I wanted to share my train of thought with you.
In my case I'm patching existing code with a variable that is used to skip already existing nested if-statements. The main function keeps running before and after the statement.
Original Code:
if(bValidateA){
}elseif(bValidateB){
}elseif(bValidateC){
}
// ... code continues with variables set inside the statements.
Now we want to add a global Parameter to not validate anything. What are my options and why do they suck?
Solution A sucks because much work and less easy to read:
if(!bValidateNothing && bValidateA){
}elseif(!bValidateNothing && bValidateB){
}elseif(!bValidateNothing && bValidateC){
}
Solution B sucks because empty if-statement:
if(bValidateNothing){
// empty
}elseif(bValidateA){
}elseif(bValidateB){
}elseif(bValidateC){
}
Solution C sucks because it becomes too nested (in my case there have been some additional ifs in the original code):
if(!bValidateNothing){
if(bValidateA){
if(xx){
}elseif(xy){}
}elseif(bValidateB){
}elseif(bValidateC){
}
}
Solution D, the technically cleanest solution by adding additional functions, sucks because you need to split your code, which needs a lot of time, and may result in new errors.
(no pseudocode)
So, to answer the question "accepted and safe": it works, it's readable, safe and quick. Sometimes that has to be enough, considering the alternatives. If you have the time to avoid using it, I'd probably still recommend that instead.
Funny enough, the time I saved by using this quick way to implement my logic, has now been successfully spent adding my cents to this ten year old already answered question.
Just don't write a block for a case you don't want to handle.
If you only want to do something when console exists, then do that:
if(typeof console !== 'undefined'){
// your code
}
// else if(typeof console === 'undefined'){}
// you don't need that second part
Or maybe I didn't quite get your issue?
Same as Pioul's answer, but I'd add that imo checking existence in javascript looks much tidier with the !! (notnot) operator.
if(!!console){
// your code
}
// else if(!console){}
// you don't need that second part
Sometimes it is useful to have debugging information printed out:-
if(typeof console !== 'undefined'){
console.log("debug info");
}
Then, before releasing the code, simply comment out all the console.log's
// console.log("debug info");
This can be done with a macro.
It will leave an empty if statement. But this is not a compilation error so that's OK.
Note, that if you're going to comment out the line it is important that braces are used. Otherwise you'd have the next line dependent on the if statement which would be a bleeding shame.
Using an empty if statement can be a valid and accepted practice in certain situations.
For example, when working with a try-catch block, you may use an empty if statement to handle specific errors without disrupting the rest of the function. Additionally, it can be used for performance optimization by short-circuiting the evaluation of certain conditions.
Make sure that when using an empty if statement, it is properly commented to provide context and explanation for its use.
Example:
try {
// code that may throw an error
} catch (error) {
if(error instanceof SpecificError) {
// handle specific error without disrupting the rest of the function
}
}
Another example:
if(isFirstConditionTrue && isSecondConditionTrue && isThirdConditionTrue) {
// Do something
} else if(isFirstConditionTrue && isSecondConditionTrue) {
// Do nothing, because third condition is false
} else {
// handle other conditions
}
It's always a good practice to add comments explaining the purpose of each empty if statement and why you chose to use it in a certain scenario. It's not generally considered bad style as long as it serves a specific purpose and is well documented.

Are empty true blocks an idiom in JavaScript?

I just came across code that looks like this:
if (foo == "bar"){}else{
}
Is there a good reason for someone to write it that way instead of
if (foo != "bar") {
}
or am I just dealing with a raving lunatic (this is my assumption based on other things in the code).
[Edit]
There is no such convention in the JavaScript community. This is just bad code.
[Original "Answer" Below]
I prefer to use the following syntax when I am leaving a project:
if (foo == "bar") { /* 100 or so spaces */ } else {
}
The } else { segment is hopefully obscured off screen by text editors so that the code does the exact opposite of what it seems. This way I can ensure that the remaining development team curses my name and would never consider me for future development or support. =D
I don't see why JavaScript code should be different in this respect from any C-heritage language. I've not encountered this idiom before, and I really don't like it. I need to mentally parse the thing twice to make sure I've understood.
The only analogue I can think of is an empty default in a switch statement,with a copious comment to say "I thought about this and it's just fine."
If one of my developers wrote code that way, I'd throw it back at them with a reprimand and a copy of "Javascript: The Good Parts." I can't think of a single good reason for doing that.
Also, they should have written their comparison as if (foo === "bar"). Much better practice.
Edit a year and a half later:
Out of boredom I knocked together a jsperf just to see if there was any noticeable performance difference between the two methods shown in the OP, and [SPOILER WARNING] no there isn't.
http://jsperf.com/empty-blocks-in-if-else-statement
I have done it before.
This is when I might want to add some debug statements later.
Yes sure he could have done
if (foo != "bar"){
//something
}else{}
But isn't that just the same thing?
Back to the code you saw.
So what the programmer probably did is:
if (foo == "bar"){}
else{/*something*/}
Then later on when he wanted to add some debug information into the 1st part he would.
The logic still works and it is not flawed in the least bit. (in my opinion)
It's confusing for two reasons. The syntax is confusing because he's evaluating foo == bar just to do ... nothing? It seems unnecessary not to use the syntax you suggested. Visually it's also confusing because the empty block and the if evaluation are on one line, so if I were reading this code later I might gloss over things and assume the statement read as
if (foo == "bar"){
}
Which is the exact opposite of the code's intention. One possible explanation for this is that the programmer intended to go back and implement some code for foo == bar, but either didn't or forgot to do so.
My vote is for lunatic.
There is no good reason to do that.
On a side note, however, keep in mind that with loops there are sometimes cases where an empty block may be acceptable:
var i;
for (i = 0; document.getElementById("box" + i).value != ""; i++) { }
// do something with i
I tend to write chained if's like this:
if (a) {
} else if (b) {
// do something
} else if (c) {
// do something
} else if (d) {
// do something
}
Rather than:
if (!a) {
if (b) {
// do something
} else if (c) {
// do something
} else if (d) {
// do something
}
}
This makes the code more neat IMO.
Does it make sense?

Is it worth the effort to have a function that returns the inverse of another function?

I have recently added a HasValue function to our internal javascript library:
function HasValue(item) {
return (item !== undefined && item !== null);
}
A during a convorsation with a coworker, we came up with the idea of also adding another function that would basically just be the inverse: perhaps HasNoValue, or IsNothing
If we ended up doing that we would have:
function HasNoValue(item) {
return (item === undefined || item === null);
}
function HasValue(item) {
return !HasNoValue(item);
}
However, we're not sure whether it is more readable to have both, or HasValue.
Which is more readable/preferred?
A:
if (HasValue(x) && !HasValue(y))
B:
if (HasValue(x) && HasNoValue(y))
I vastly prefer A to B. "!" is a programming idiom that should be understood by all.
If !HasValue(y) and HasNoValue(y) are guaranteed to be logically equivalent over the entire input range of y, then I would greatly prefer !HasValue(y).
I would hesitate to even have a function named HasNoValue(y) because inevitably someone will write !HasNoValue(y).
I'm voting "A" by far.
The additional maintenance burden of doing this for each and any boolean return function isn't worth it versus the well-understood and quite readable "!", and in fact I believe "B" is actually less readable, since it's so easy to miss the "No" in the middle of the name.
I know I'll be quite alone with this opinion and if I'd be faced with this choise in a collaborative project, I'd surely go with A, since it's quite obvious it's the right thing to do, but I have to say I do appreciate the verbosity of option B. Words are just infinitely easier to read and understand than symbolics, even if it's something as mundane as our beloved ol' exclamation point.
Especially now that IDE's have so much better intellisense than before, I usually tend to opt for far more verbosity than before with all naming. 9 times out of 10, readability trumps small performance differences, hands down.
Just for the sake of having less lines of code and because your function returns a Boolean, I'd say to go with method A. If you have to worry about readability, you can always try:
if ( HasValue(x) && !(HasValue(y)) )
I would say option A is clearer, you know exactly what it means.
I would stick with option A but thats just me.

Categories

Resources