Comparison position in conditionals JavaScript [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 months ago.
Improve this question
I'm curious about, why some programers compares before the value than the variable ?
For example, if I want to create a simple if, I'll do something like this:
const foo = 'success';
if(foo === 'success') {
console.log('works fine!');
} else {
console.log('don\'t work');
}
BUT I've seen some programers that do that:
const foo = 'success';
// Note the position of the success value!
if('success' === foo) {
console.log('works fine!');
} else {
console.log('don\'t work');
}
I want to know which way is better and WHY ?
Thanks.

It's Yoda conditions. Programmers do for null safe.
I try compare strings. If my variable null and I try call method of includes() I will get exception, but if I call includes() for literal it's save from exception.
const someString = null;
// I will get exception
if (someString.includes("literal")) {
}
// Null safe
if ("literal".includes(someString)) {
}
BUT: if you matter know about something variable that it's null, then not need use yoda condition. Try handle this exception.

Related

Is it best practice to have an if - else block inside the else block [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have a Map = {'key - string', value as object} and a List[] and a String 'TEST',
Here I need to check two checking based on the String in the map and the Array,
For Example,
if(Map.has('TEST')) {
Need to do some logic
} else {
if(Array.includes('TEST') {
Need to do some manipulation
} else {
Need to do some manipulation
}
}
I have tried like above to achieve my need. Is it a best practice? Advice me.
if(Map.has('TEST')) {
Need to do some logic
} else if(Array.includes('TEST')) {
Need to do some manipulation
} else {
Need to do some manipulation
}
Use Else If
More Examples
EDIT1: Since you said you Need to check 2 Things Maybe this suits even more but im not sure your Question is very vague.
// || = OR
if(Map.has('TEST') || Array.includes('TEST')) {
Need to do some logic
} else {
Need to do some manipulation
}

What is the best way to find the first occurrence of an item in a collection and update it [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a collection in Javascript/Typescript
[
{"order":1,"step":"abc:","status":true},
{"order":2,"step":"xyz","status":true},
{"order":3,"step":"dec","status":false},
{"order":4,"step":"pqr","status":false},
{"order":5,"step":"tuv","status":false}
....
];
I need to write a function that every time its called it identifies the first occurrence of a false (Order:3 in the above example) and updates it to true. If the above method is called again now the next element (order:4 ) would have been updated. The steps that are false will always be below steps that are completed i.e true.
What's the best way (simplest, less code and elegant) to write this function? I can manually loop through using for each of the items in the collection, check for the first occurrence of false and then update it.
In ES6 you can use this:
yourArray.find((element) => !element.status).status = true;
See find() and its compatibility table.
And note that this will fail if there is no entry with status: false. A quick and dirty fix could for example look like the one below. But that entirely depends on your use case.
(yourArray.find((element) => !element.status) || {}).status = true;
Pretty much what you described is how you would do it:
for (let order of orders) {
if (!order.status) {
order.status = true;
break;
}
}
When you look for the matching occurance you require, then insert a 'break' statement to stop the search.
Example:
for( var i=0; i<recs.length; i++ ) {
if ( recs[i]['status'] == false ) {
recs[i]['status'] = true;
break;
}
}
You can use Lodash find method to find the first occurence of false status.
Sample Code
_.find(users, function(object) { return object.status === false });
lodash find documentation link

Which piece of code is generally more accepted? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I was wondering which of the pieces of code below are generally more accepted or maybe even better:
function doStuff(check) {
if(!check) {
return "blablabla";
} else if (check >= 5) {
return "blablabla";
} else {
return "blablabla";
}
}
or
function doStuff(check) {
if(!check) {
return "blablabla";
} else if (check >= 5) {
return "blablabla";
}
return "blablabla";
}
Since the return statement makes the JavaScript interpreter leave the current function it is in I don't see a reason to put an else statement at the end of the second example because the only way to get there is if all previously mentioned comparisons resulted false anyways.
Is this just a case of pick whatever the hell you like but be consistent at it or is there an actual rule for this?
I would even go one step further:
function doStuff(check) {
if(!check)
return "blablabla";
if (check >= 5)
return "blablabla";
return "blablabla";
}
But this is a matter of taste. While I find it better to omit unnecessary else statements, I have also heart colleagues say that you should always put this else there to make the control structure clearer... But in such simple cases I would not bother putting them in.
For numeric values, though, I would prefer check == 0 to !check.

Clean up if statement Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I do have jQuery and wouldn't mind using it but here's the code I would like to clean up:
if (parent.uglyChild.uglyChild.uglyChild.uglyChild.data == null) {
parent.uglyChild.uglyChild.uglyChild.uglyChild.data = new app.newData();
}
The only way I know how to clean it up is:
var data = parent.uglyChild.uglyChild.uglyChild.uglyChild.data;
if (data == null) { data = new app.newData()}
I have always wondered if there was a way to do something like:
parent.uglyChild.data = parent.uglyChild.data.isNull ? return : new app.newData();
I can't wait to see the shorthand tricks you guys know! :)
You could do something like
var ugly = parent.uglyChild.uglyChild.uglyChild.uglyChild;
ugly.data == null && (ugly.data = value)
you can cache the nearest object to avoid repetition, thanks to JS's leaky assignments:
if ( (x=parent.uglyChild.uglyChild.uglyChild.uglyChild).data == null) {
x.data = value;
}
If you want to use the ternary operator, you could always reassign the value.
parent.uglyChild.data = (parent.uglyChild.data == null) ? null : value;

False or null for error checking -Javascript [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I was wondering which of the two is appropriate:
error = null or error = false
if(error) {
//handle it
}
Is it a matter of preference/coding style or does one have an actual advantage over the other. Is it contextual? Is there a consensus at all on the issue?
Thank you.
Both the examples you have given will evaluate to false.
In this simplistic example you have given there is no difference - both null and false will trigger the conditional expression.
Let me try again.
error = null;
if (!error === true) {
// this will work
};
if (error === false) {
// this will not work
};
Here is a fiddle you can test in.
Both statements evaluate to false.
var error = false; will be appropriate if you only want to know about error or not. If some cases, you may want to have error message in the error, then you can assign to null.
Both are valid. The choice is based on purpose of error variable.
I'd rather use the error variable as a string, then you can add messages to help debugging, telling the developer where the problem occured.

Categories

Resources