How would I should I shorten the following piece of code? - javascript

I have the following piece of code. It is simple and does the job... But it's too lengthy for my liking.
if ( isInputValid( userInput ) ) {
return userInput;
} else {
console.log('User Input is Invalid!');
}
Normally, I would just be able to use a ternary operator. However, in this case, I can't.
// not possible, invalid
isInputValid( userInput ) ? return userInput : console.log('User Input is Invalid!');
But, is there another way to shorten and further simplify the if and else statement? Anything like the fat arrow syntax, etc?
Much appreciated.

Seems like you have a few options. First, since you appear to be returning from a function, you could shorten your initial code by simply omitting the else part.
if ( isInputValid( userInput ) ) {
return userInput;
}
console.log('User Input is Invalid!');
Now you could still use a ternary operator if you want, you just need to return the result of the ternary operator itself.
return isInputValid(userInput) ? userInput : console.log('User Input is Invalid!');

Building on #Nick's answer, a good way to shorten this code would be to simply do the following.
if ( isInputValid( userInput ) ) return userInput;
console.log('User Input is Invalid!');
Being able to remove the braces, due to it being a single statement, followed by removing the else as console.log() will really only be executed if the previous statement is false anyway. So, it renders the else unnecessary.
Short and simple, beautiful!

Related

Why some statements can't be used with boolean operators

I like to use this style for single line conditional function calls:
debug && console.log('Debug is on');
It's much more terse than it's if counter part.
However some statements dont work, e.g. return and debugger:
error && return null
(value == '43') && debugger;
Why does it not work for the above statements? Instead I use:
if (error) return null;
if (value == '43') debugger;
For the same reason you can't say things like these:
const foo = if (bar) { 5 } else { "hi" };
const baz = try { somethingThatCanFail(); } catch (err) { console.error(err); fallback(); };
Javascript, like a lot of other programming languages, retains the difference between an expression and a statement. You can't use a statement in a place where syntactically an expression is expected.
Expressions evaluate to a value, even if that value is undefined. An invocation of a function is an expression. Even an assignment is an expression. But things like try, return, and if are statements.
In some programming languages (notably most functional languages) everything is an expression and evaluates to a value.
When you use the boolean operator, it has to be an expression, not a statement. Some of those keywords/operators are only valid full statements
Here is a related question to explain more
Why can't we have return in the ternary operator?

Can you use the return statement as an expression

Recently I've discovered that sometimes it is more convenient to
condition && fnWhenTrue()
than
if(condition){
fnWhenTrue()
}
Honestly I've fallen in love with it and started using it wherever it makes sense. However I am unable to do a
condition && return
As return is a statement and not an expression. Is there a way around this or is this just not a valid use case and I should stop.
I am able to achieve similar effect using an inline if like this
if(condition) return
But it's just not the same.
Thanks in advance
No, return is not an expression in JavaScript / ECMAScript at the time of this answer.
If you don't want to write several lines / lengthy code, you can use the short if notation:
if (condition) return;
Which is only 2 characters longer than condition && return;!
Just as a reminder, val = exp1 && exp2 is an expression that is roughly equivalent to:
let val;
if (exp1) {
val = exp2;
} else {
val = exp1;
}
(with some main difference that exp1 is evaluated 2 times in my above example, whereas only once in exp1 && exp2).
Just as something to convince you that is probably intended in JS language design, as you can do:
let someResult;
// later...
someResult = exp1 && exp2;
then what would someResult got as value if you had a return instead of exp1 and exp2?

Do I need a last `else` clause in an `if...else if` statement? [duplicate]

This question already has answers here:
Why would Javascript `if...else if` not end with an `else`?
(8 answers)
Closed 6 years ago.
Every if...else if example I’ve seen includes a final else clause:
if (condition1) {
doA();
} else if (condition2) {
doB();
} else if (condition3) {
doC();
} else {
noConditionsMet();
}
alwaysDoThis();
I understand that this is basically syntactic sugar for nested if...else statements:
if (condition1) {
doA();
} else {
if (condition2) {
doB();
} else {
if (condition3) {
doC();
} else {
noConditionsMet();
}
}
}
alwaysDoThis();
I have never seen any examples of an if...else if that omits the last else clause. But seeing as plain if statements (without else clauses) are valid, and going by the equivalent “nested statements” above, my gut tells me that this is okay to do:
if (condition1) {
doA();
} else if (condition2) {
doB();
} else if (condition3) {
doC();
}
alwaysDoThis();
Can someone point me to a resource or example that explicitly says whether or not it’s valid?
And on another level, if it is valid, would it be recommended or is it considered “bad practice”?
The ending else is not mandatory as far as JavaScript is concerned. As for whether it is needed, it depends on what you want to achieve.
The trailing else clause will execute when none of the specified conditions is true. If the conditions are collectively exhaustive, then an else clause is entirely superfluous, except possibly to contain an assertion that catches the "impossible" condition. In your case, whether you need an else clause depends on whether you want specific code to run if and only if neither of condition1, condition2, and condition3 are true.
else can be omitted for any if statement, there is nothing special in the last if of an if/else if chain. This is documented in any JavaScript grammar, e.g. in the specification.
It is 100% valid. No, it is not bad practice. If you don't need it, don't write it.
Take the following for example:
function doStuff(data) {
if (data.something) {
// go format the data in some way
}
else if (data.somethingElse) {
// go format the data in some other way
}
// must be formatted correctly, don't do anything else
...
}
You never need an else clause. (It's hard to offer examples of something that is not necessary, so I'll leave it at that.)
edit as a comment notes, square brackets in language syntax notation usually indicate that something is optional.
No need for a else block, they are not if else statement but if statements. Consider else, elseif as an extension.
Here's a link to a sitepoint thread : click this.
And a similar thread on stackoverflow : click here

Do I need to use an "=" when using the ? : javascript shortcut?

Can someone tell me if this is valid javascript to do this:
if (wf.statusId == Status.Dirty) {
wf.createdDate
? promises.push(self.wordFormUpdateSubmit(wf, key))
: promises.push(self.wordFormAddSubmit(wf, key));
}
Would there be cases where this would not work correctly if createdDate was not defined?
Here's what this replaced:
if (wf.statusId == Status.Dirty) {
if (wf.createdDate) {
var updatePromise = self.wordFormUpdateSubmit(wf, key);
promises.push(updatePromise);
} else {
var addPromise = self.wordFormAddSubmit(wf, key);
promises.push(addPromise);
}
}
Also a related question. Would it be possible to use the same syntax with ? : to replace the need for the if () { } construct ?
Using = with ternary operator is not mandatory unless expr1 and expr2 are returning something and you want to save it in some other variable.
In your case, unless promises.push(self.wordFormAddSubmit(wf, key)) and promises.push(self.wordFormUpdateSubmit(wf, key)) are returning something that you want to save it a variable, there is no need for a =.
if (wf.statusId == Status.Dirty) {
promises.push(self[wf.createdDate ? 'wordFormUpdateSubmit' : 'wordFormAddSubmit'](wf, key));
}
wf.createdDate only true if it is not undefined or have value. so this should work fine.
if (wf.statusId == Status.Dirty) {
wf.createdDate
? promises.push(self.wordFormUpdateSubmit(wf, key))
: promises.push(self.wordFormAddSubmit(wf, key));
}
Regards
Mk
This is an example of a ternary statement, using the conditional (ternary) operator, which by definition replaces an if...else construct.
From MDN:
The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.
[source]
Both of your code samples would work the same way, ie if createdDate was undefined the second expression of your ternary statement would run (the line after the :) just like the else block of your if...else construct would run.
The title question seems somewhat unrelated, in that you would only need to use = if you wanted to save a reference to something. In this case, it does not appear that you do.
As for your follow-up question, plenty of people use ternary statements for small checks and tasks that fit on one or a few lines (I personally don't because I prefer the readability of if...else), however anything even moderately complex can quickly make your code hard to read and understand. But yes, technically, ternary statements can replace if...else blocks.
regarding the second question:
assuming you don't need to save the results in a variable, you can do:
promises.push(wf.createdDate?
self.wordFormUpdateSubmit(wf, key) :
self.wordFormAddSubmit(wf, key);
);
and even this works:
promises.push(
(wf.createdDate? self.wordFormUpdateSubmit:self.wordFormAddSubmit)(wf, key)
);

Shorthand if ? return : null

I want to achieve this:
if (full) {
return
}
else{
// nuthin
}
But shorter, something like:
full ? return : null;
But that doesn't work..
I could do:
if (full) { return }
But I like the ternary more
I expected something like full ? return to work...
I basically want to break out of the current function when the value is true...
Are there any better/working shorthands available?
The arguments of a ternary are expressions not statements.
return; is a statement so what you're proposing is not syntatically valid.
Your if statement is about as terse as you can make it: especially if you remove unnecessary braces.
Explainations
If you only want the test if true, you can use the logical AND operator && like so:
index.js:
(function(){
var full=true;
full&&alert('Glass is full');
})();
Note that in this example, nothing will happen in case var full=false;.
Source-code
JSFiddle source-code.
Codepen source-code
Pastebin source-files
So this is as short as it gets:
if full return
For those using typescript with all the bells and whistles:
if (condition) return;

Categories