I was wondering if any can help point me to resource to teach me more about logical operators, and answer a question for me. I would like (for the sake of satisfying my curiosity) to combine these nested conditional checks with logical operators into one statement.
if(obj1 != null && obj2 != null) {
if(obj1 != undefined && obj2 != undefined) {
//do something here
}
}
I have tried
if((obj1 != null || obj1 != undefined) && (obj2 != null || obj2 != undefined)) {
//do something here
}
But I don't think that works, since if obj1 or obj2 is equal to null or undefined than the or statement will evaluate to true. So the above code in the conditional would be executed if obj1 was null or undefined AND obj2 was null or undefined, which is definitely not what I want.
So how could I combine the nested conditional into one line?
Thanks!
:)
You might be overthinking. Code like
if (a) {
if (b) {
// stuff
}
}
executes stuff only if a and b are both true, so it is simply equivalent to
if (a && b) {
// stuff
}
Thus all you have to do is take your existing conditions and connect them with &&. You can write
if((obj1 != null && obj2 != null) && (obj1 != undefined && obj2 != undefined)) {
//do something here
}
Related
Can someone please clarify below issue.
Below validation throw NULL pointer error when pass null in myVar. It is because of !myVar.isEmpty()
if (myVar!= null || !myVar.isEmpty() ) {
some code///
}
Below works though as expected,
if (myVar!= null) {
if (!myVar.isEmpty()) {
some code///
}
Any other way of having both steps together.
If .isEmpty() is used on a string, then you can also just use Groovy
"truth" directly, as null and also empty strings are "false".
[null, "", "ok"].each{
if (it) {
println it
}
}
// -> ok
if ( myVar!= null && !myVar.isEmpty() ) {
//some code
}
the same as
if ( !( myVar== null || myVar.isEmpty() ) ) {
//some code
}
and to make it shorter - it's better to add method like hasValues
then check could be like this:
if( myVar?.hasValues() ){
//code
}
and finally to make it groovier - create a method boolean asBoolean()
class MyClass{
String s=""
boolean isEmpty(){
return s==null || s.length()==0
}
boolean asBoolean(){
return !isEmpty()
}
}
def myVar = new MyClass(s:"abc")
//in this case your check could be veeery short
//the following means myVar!=null && myVar.asBoolean()==true
if(myVar) {
//code
}
So I want to check if a variable is undefined in node.js. So far I work like this:
if(typeof object.data.items[1] === 'undefined')
{
break;
}
else
{
console.log("Defined");
}
But it gives me this error:
"TypeError: Cannot read property 'data' of undefined".
Any ideas on how to bypass this error while still checking if it's undefined?
check both object and object.data is defined first.
if(object && object.data && typeof object.data.items[1] === 'undefined')
{
break;
}
else
{
console.log("Defined");
}
or
if(!object || !object.data || typeof object.data.items[1] === 'undefined')
{
break;
}
else
{
console.log("Defined");
}
It seems that object variable is undefined too. Try the following code:
if(
typeof object === 'undefined' ||
typeof object.data === 'undefined' ||
typeof object.data.items[1] === 'undefined')
{
break;
}
else
{
console.log("Defined");
}
if(!_.get(object,['data','items',1]))
{
break;
}
When you try to access a property of JSON object you have to ensure that left side of your dot operator must have some value but not undefined or null. i.e.
If you want to access a.b.c.d then you have to make sure that each left side property has some value. You can use #rijin's answer.
I am confused why this if statement will throw a JS error. Why isn't the function running as soon as it returns true?
res.locals.user = null;
console.info(res.locals.user === null); //true
if (res.locals.user === null && res.locals.user.level > 5) {
The && in your if statement is analogous to this:
res.locals.user = null;
console.info(res.locals.user === null); //true
if (res.locals.user === null) {
// at this point you know that res.locals.user is null
if (res.locals.user.level > 5) {
// won't get here because res.locals.user.level will throw an exception
}
}
If the first part of an && comparison evaluates to truthy, then the second part will also be evaluated since for the whole statement to be true, both pieces of the statement must be truthy.
It appears that you may want this instead:
res.locals.user = null;
console.info(res.locals.user === null); //true
if (res.locals.user === null || res.locals.user.level > 5) {
// will get here because only the first term will be evaluated
// since when the first term evaluates to true, the || is already satisfied
}
Or since I'm not quite sure which logic you want, maybe you wanted this:
res.locals.user = null;
console.info(res.locals.user === null); //true
if (res.locals.user !== null && res.locals.user.level > 5) {
// will not get here because res.locals.user doesn't pass the first test
// won't throw an exception because 2nd term won't be evaluated
}
Because the first part of the evaluation is true, so it goes on to evaluate the next part which will then always throw an exception as the first part was true. It's like a paradox :)
There are languages where the the && only executes the second comparison if the first is true (like java). However, what you wrote would fail in any language. You can't be null and level>5 all at once.
I have the following method where I want to test the event.status property only if status has been passed in:
def findEvent(String desc, String status = null, Collection events) {
return events.find {
it.description == desc && \\If status is not null: it.status == status
}
throw new Exception("Review Event Record Not Found: ${desc}")
}
I thought it could be done like this, but it doesn't seem to work:
def findEvent(String desc, String status = null, Collection events) {
return events.find {
it.description == desc && (status != null ?: {it.status == status})
}
throw new Exception("Review Event Record Not Found: ${desc}")
}
Is there any way this could be done? Or do I have to go back to something like this:
if (status != null) {
return events.find {
it.description == desc && it.status == status
}
} else if (status == null) {
return events.find {
it.description == desc
}
}
Is there some kind of best practice?
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.
I have a tree structure and I want to find all nodes matching a given criteria. Each time I call the find function, it returns next matching node. Children are searched by recursive function call.
For some reason a key comparison of pointers fails for this implementation. Please see the code below, I have pointed out the failing comparison.
HtmlTag* HtmlContent::FindTag(string tagName, string tagParameterContent)
{
if (tagName.empty() && tagParameterContent.empty())
return NULL;
if (this->startTag == NULL)
return NULL;
this->findContinue = this->FindChildren(this->startTag, &tagName, &tagParameterContent);
return this->findContinue;
}
HtmlTag* HtmlContent::FindChildren(HtmlTag* firstTag, string* tagName, string* tagParameterContent)
{
HtmlTag* currentTag = firstTag;
HtmlTag* childrenFound = NULL;
while (currentTag != NULL)
{
if (!tagName->empty() && *tagName == currentTag->tagName)
{
if (tagParameterContent->empty() || currentTag->tagParameters.find(*tagParameterContent, 0) != -1)
{
if (this->findContinue == NULL)
break; // break now when found
else if (this->findContinue == currentTag) // TODO why this fails?
this->findContinue == NULL; // break on next find
}
}
if (currentTag->pFirstChild != NULL)
{
childrenFound = this->FindChildren(currentTag->pFirstChild, tagName, tagParameterContent);
if (childrenFound != NULL)
{
currentTag = childrenFound;
break;
}
}
currentTag = currentTag->pNextSibling;
}
return currentTag;
}
VC++ compiler accepts this code but for some reason I can't put a breakpoint on this comparison. I guess this is optimized out, but why? Why this comparison fails?
I think that you shoud replace == with = in assignment after comparison. Compiler optimalized this whole section because it doesnt do anything useful.