Javascript long else / if statement in a shortest way - javascript

I have written an else / if statement in my plugin but for optimization (less code) I want it to be shorter.
if ( self.first() ) {
if ( self.second() ) {
self.run();
}
else {
self.other_run();
}
}
else {
return false;
}
Example
if ( check cookie is true ) {
if ( check timezone is true ) {
run sth
}
else {
run other thing
}
}
else {
do nothing
}
What about?
if ( self.first() ) {
self.second ? self.run() : self.other_run();
}
else {
return false;
}
Is it ok to write it like that?
return self.first() ? ( self.second() ? self.run() : self.other_run() ) : false;

self.first() ? ( self.second() ? self.run() : self.other_run() ) : false;
Should work fine, but I'm not sure why you'd want to obfuscate your code like that.

(Keep in mind that "shorter" code isn't always "better" code.)
That may work, with some explicit parenthesis to separate your wrapped statements. Though it's not really easier to read/understand. How about something like this?:
if (self.first() && self.second()) {
self.run();
return;
}
if (self.first()) {
self.other_run();
return;
}
return false;
This follows Martin Fowler's refactoring pattern called Replace Nested Conditional With Guard Clauses.
This also makes it more clear that your function isn't always returning a boolean value. (Something I didn't immediately notice until I wrote this.) Perhaps you mean to do so (a bug which wasn't noticed in the overly-brief version of the code)?:
if (self.first() && self.second()) {
self.run();
return true;
}
if (self.first()) {
self.other_run();
return true;
}
return false;
Naturally, this code is obviously fake just to demonstrate a point. But if the conditional clauses do start to get unwieldy, you can always extract them into their own functions:
if (somethingIsTrue()) {
self.run();
return true;
}
if (somethingElseIsTrue()) {
self.other_run();
return true;
}
return false;

Related

shorten if conditions in js

I want to shorten the conditions of a javascript if but I don't know how I can achieve it
code:
if ((!emailValidation() || (!nameValidation()) || (!surnameValidation()) || (!addressValidation()) || (!cityValidation()) || (!postalCodeValidation()))) {
}
I have the conditions defined in this way:
let surnameValidation = () => {
if (apellidoUsuario.value.length == 0) {
surnameError();
return false;
}
else if (apellidoUsuario.value.length == 1) {
surnameError();
return false;
}
else {
apellidoUsuario.focus;
apellidoUsuario.style.border = '0';
apellidoUsuario.style.backgroundColor = 'transparent';
apellidoUsuario.style.outline = '1px solid #00ffb1'
apellidoUsuario.style.transitionDuration = '0.4s'
return true;
}
I appreciate any help! :)
You can remove all unnecessary parenthesis in your if condition:
if (
!emailValidation() ||
!nameValidation() ||
!surnameValidation() ||
!addressValidation() ||
!cityValidation() ||
!postalCodeValidation()
) {
}
Other than that, there's not really a clean, readable way to shorten your code.
Proposition #1:
I would probably get those validations into a variable or function:
validations() {
return [
emailValidation(),
nameValidation(),
surnameValidation(),
addressValidation(),
cityValidation(),
postalCodeValidation()];
}
and then I would:
if(validations().some(x=> !x)){
...
}
since validations return an array you can just use the some operator to find any invalid value.
Proposition #2:
I particularly would:
valid() {
return [
emailValidation(),
nameValidation(),
surnameValidation(),
addressValidation(),
cityValidation(),
postalCodeValidation()].every(x => x === true);
}
and then I would:
if(!valid()){
...
}
It is always cleaner to use true conditions on if statements instead of false ones.
References: Clean Code - Uncle Bob.

Is it better to create a function that is only called in one place, or use an arrow function?

For example, if I have an arrow which I want to call filter() on, is it better to do something like this:
tasks.filter((task) => {
if (task.completed && hideCompletedTasks) {
return false;
} else {
return true;
}
}
)
or extract the function logic out and call the function one time.
tasks.filter((task) => filterCompletedTasks(task));
function filterCompletedTasks(task){
if (task.completed && hideCompletedTasks) {
return false;
} else {
return true;
}
}
It is not efficient or more readable to use if on booleans to return true or false:
Why not
const filterCompletedTasks = task.filter(task => task.completed && hideCompletedTasks);
Use the first logic i.e.
tasks.filter((task) => {
if (task.completed && hideCompletedTasks) {
return false;
} else {
return true;
}
}
)
It depends on your needs, if you're only going to use that function only for that special ocassion, there's no need to take out the function (unless its too big and you want to isolate it), but if you're gonna reuse that function in other filters, then it'd be a good idea creating a separate function for that.
You can use this approach,
tasks.filter((task) => {
if (task.completed && hideCompletedTasks) {
return false;
} else {
return true;
}
}
);
Same logic can be written as,
tasks.filter(task => task.completed && hideCompletedTasks);

Trying to solve If/else problem with specific string and boolean

Problem
I've tried multiple avenues and watched videos. I'm stuck...
function exerciseThree(typeOfPizza){
let lovesPizza;
// In this exercise, you will be given a variable, it will be called: typeOfPizza
// You are also given another variable called: lovesPizza;
// Using an if/else statement assign lovesPizza to true if typeOfPizza is 'pepperoni', assign it to false if it is 'olives'
What I've tried:
if (lovesPizza==='pepperoni') {
// The value is empty.
return true;
}
else {
(lovesPizza==='olives')
return false;
}
Another attempt
// if(lovesPizza===pepperoni){
// return true
//}
//else (lovesPizza===olives){
// return false
// }
Another one
//if (lovesPizza.equals(pepperoni))
// return "true";
//else (lovesPizza.equals(olives))
// return "false"
As the comments say, you're looking for if / else. You should also double check your reading of the question, you had your checking / assigning variables the wrong way around
function exerciseThree(typeOfPizza){
let lovesPizza;
if (typeOfPizza === 'pepperoni') {
lovesPizza = true;
} else if (typeOfPizza === 'olives') {
lovesPizza = false;
}
console.log('lovesPizza:', lovesPizza);
};
exerciseThree('pepperoni');
exerciseThree('olives');
I would highly recommend using a switch statement in this case here. Switch statements run faster and are easier to work with in my opinion.
But to point out what you're doing wrong:
Here you are checking if lovesPizza has the value of pepperoni. But you should be checking typeOfPizza. This is why you're most likely getting undefined:
if (lovesPizza==='pepperoni') {
// The value is empty.
return true;
}
else {
(lovesPizza==='olives')
return false;
}
Check out how this looks with a switch statement.
function exerciseThree(typeOfPizza) {
switch (typeOfPizza) {
case 'pepperoni':
return true;
case 'olives':
return false;
default:
return false;
}
}
exerciseThree('pepperoni');
exerciseThree('olives');
Your else statement needs an if
if(somethingisTrue)
{
return "it is true";
}
else if(somethingelseistrue)
{
return "no the other thing was true";
}
else
{
return "nothing is true"
}
Also === checks the strings equal and are both strings. It is often better to make sure the if is case insensative
if(!typeOfPizza)
{
//raise an error as null was passed in
return "false"
}
else if(typeOfPizza.toLowerCase().trim()==="pepperoni"){
{
return true..... you can build the rest
I often write a function (prototype) called cleanString or compareString to perform all the normal cleaning up of strings.
A simple solution is but doesn't use ifs as asked.
function exerciseThree(typeOfPizza){
let lovesPizza= typeOfPizza==="pepperoni";
return lovesPizza;
}
I certainly hope you teacher is playing a trick on you.
There is no sane suggestions what to do if you send for instance 'ham' into it, and not handle all possibilities are just sloppy.
let lovesPizza;
function exerciseThree(typeOfPizza){
if(typeOfPizza === 'pepperoni') {
return true;
} else if (typeOfPizza === 'olives') {
return false;
} else {
return undefined;
}
}
lovesPizza = exerciseThree('pepperoni');
console.log(lovesPizza); // true
lovesPizza = exerciseThree('olives');
console.log(lovesPizza); // false
lovesPizza = exerciseThree('ham');
console.log(lovesPizza); // undefined

Issue with nested if statement (within function) in Javascript

first time here and I've run into an issue... idk if it's my syntax or my logic is completely wrong...
var hasExperience;
var amountOfExperience;
function employed(hasExperience,amountOfExperience) {
if(hasExperience === true){
if(amountOfExperience > 5)
return true;
} else {
return false;
}
}
It doesn't seem to want to return false if the first two if statements aren't met... anyone can help?
Thanks!
If you need both of the if statements to evaluate to true, you should write it like this:
if(hasExperience === true && amountOfExperience > 5){
return true;
} else {
return false;
}
In your example, if(hasExperience === true) then you run the code inside the if block, else run the code inside the else block. It's important to understand that this is completely independent of what's inside the if block.
if(hasExperience === true){
// code inside if block
} else {
// code inside else block
}
The code inside the if block happens to be another if statement that will return true if(amountOfExperience > 5), and does nothing otherwise. Again, this is independent of the other if statement.
if(amountOfExperience > 5)
return true;
Using &&, means that both statements have to evaluate to true in order to execute the code inside of the if block. You can read more about this here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
Also, as some others have stated, you can just write your function like this:
function employed(hasExperience,amountOfExperience) {
return hasExperience === true && amountOfExperience > 5;
}
Since your evaluating (hasExperience === true && amountOfExperience > 5) as a boolean and returning that boolean, you can avoid the if statement all together.
Try experimenting with this a little bit more to understand what's going on.
Update based on comment:
You could also accomplish this using the nested if, but this makes the code messy and difficult to read.
if (hasExperience === true) {
// only hasExperience is true
if (amountOfExperience > 5) {
// hasExperience is true and amountOfExperience is greater than 5
return true;
} else {
// hasExperience is false and amountOfExperience is less than 5
return false;
}
} else {
// hasExperience is false and we have no idea what amountOfExperience is
return false;
}

javascript ternary operator "chaining"

I'm trying to write something like this with a ternary operator (needed because of jsx syntax constraints)
if(!this.state.msg) {
if(this.state.ask.length != 0) {
// do stuff
} else {
// do stuff
}
if(this....) {
//do stuff
} else {
// ...
}
} else {
//nothing
}
So I tried this dumb
!this.state.msg ? this.state.ask.length != 0 ? //do stuff : "" this.state... ? //do stuff : //do other stuff : //nothing
But it's obviously not the right way to go.
Any help very welcomed. thanks in advance.
Your true branch has two components; you can separate them with commas (parenthesized, since the comma has weaker associativity than the ternary operator). So
!this.state.msg ?
(
this.state.ask.length != 0 ? /*stuff*/ : /*stuff*/,
this... ? /* stuff */ : /* ... */
) : /* nothing */
Or, since the else branch is doing "nothing", you could replace the ternary operator at the top level with a simple and:
!this.state.msg &&
(
this.state.ask.length != 0 ? /*stuff*/ : /*stuff*/,
this... ? /* stuff */ : /* ... */
)
You are wrong in your assertion that JSX limits you in this way - read this doc page and you will see that you can use something like this:
{(() => {
// My awesome multi-step code
})()}
Maybe it'd help to add another perspective. It's very rare that you would actually need to use the ternary operator with JSX. In this case, I would consider moving all of this logic out into a separate function.
helperFunction: function() {
if(!this.state.msg) {
if(this.state.ask.length != 0) {
// return stuff
} else {
// return stuff
}
if(this....) {
// return stuff
} else {
// ...
}
} else {
// nothing
}
}
Then you'd be able to use your helper function from inside your render method.
React.createClass({
helperFunction: function() {
// ...
},
render: function() {
return (
<div>
{this.helperFunction()}
</div>
);
}
});
Your helper function can return values that can be used for attributes, or it can return other JSX components. Often I find it helpful to move code out of patterns that look like this:
render: function() {
return (
condition === 'example' ?
<MyComponent attr={this.props.example} onChange={this.props.onChange} /> :
<MyOtherComponent attr={this.state.example} onChange={this.state.onChange}/>
);
}
To code that looks like this:
helper: function(condition) {
if(condition === 'example') {
return (
<MyComponent attr={this.props.example} onChange={this.props.onChange} />
);
}
else {
return (
<MyOtherComponent attr={this.state.example} onChange={this.state.onChange}/>
);
}
},
render: function() {
return this.helper(condition);
}
Or even better in the case of string equality checking.
helper: function(condition) {
const default = <MyOtherComponent attr={this.state.example} onChange={this.state.onChange}/>
const conditions = {
example: <MyComponent attr={this.props.example} onChange={this.props.onChange} />,
example2: <MyComponent attr={this.props.example} onChange={this.props.onChange} />,
example3: <MyComponent attr={this.props.example} onChange={this.props.onChange} />,
};
return conditions[condition] || default;
},
render: function() {
return this.helper(condition);
}
This way gives you most of the power of a switch statement, but terser syntax too, it lets you elegantly select from a large number of conditional components. The same code written with if statements (regular or ternary) would be much more verbose.
For verbosity, clarity of expression and maintainability, I would not recommend converting if-else to ternary expression. Try to keep your code simple even at the expense of few extra lines.
Here it is if you just want to learn
!this.state.msg ?
(this.state.ask.length != 0 ? //do if stuff : //do else stuff),
(this.some == 0 ? //do 2nd if stuff : //do 2nd else stuff)
:
Visualizing it helps.
!this.state.msg ?
? this.state.ask.length != 0)
// do stuff
:
// do stuff
:
this.... ?
//do stuff
:
// ...

Categories

Resources