TheLoneWolf91193
TheLoneWolf91193

Reputation: 416

javascript logical operator && not working

Hi I'm calling a function bound to a html element using angularjs. This function contains a simple if statement which evaluates to unexpected result.

scope.submit=function(){
  var reqFirstDate = dateFilter(scope.date.first, scope.df);
  var reqSecondDate = dateFilter(scope.date.second, scope.df);
  var reqThirdDate = dateFilter(scope.date.third, scope.df);
  console.log("First :"+ reqFirstDate >= dateFilter(scope.minDat, scope.df)); // prints: true
  console.log("Second: "+ reqSecondDate >= dateFilter(scope.minDat, scope.df));// prints: true
  console.log("Third :" + reqThirdDate >= dateFilter(scope.minDat, scope.df));// prints : true
  console.log("Final condition: "+reqFirstDate >= dateFilter(scope.minDat, scope.df) && reqSecondDate >= dateFilter(scope.minDat, scope.df) && reqThirdDate >= dateFilter(scope.minDat, scope.df)); // prints: false
  if (reqFirstDate >= dateFilter(scope.minDat, scope.df) && reqSecondDate >= dateFilter(scope.minDat, scope.df) && reqThirdDate >= dateFilter(scope.minDat, scope.df)) { 
   //doSomething 
  }               
}

The Final condition evaluates to false.How is that possible?

Upvotes: 0

Views: 514

Answers (1)

Paolo
Paolo

Reputation: 15827

The plus operator + has higher prececedence over >= so this expression (for example)

"First :"+ reqFirstDate >= dateFilter(scope.minDat, scope.df)

is evaluated as if it were written

( "First :"+ reqFirstDate ) >= dateFilter(scope.minDat, scope.df)

that is obviously not intended.

Using parentheses properly let you fix this:

"First :"+ ( reqFirstDate >= dateFilter(scope.minDat, scope.df) )

Your code needs the console.log lines to be fixed accordingly:

console.log("First :" + ( reqFirstDate >= dateFilter(scope.minDat, scope.df ) ) );
console.log("Second: "+ ( reqSecondDate >= dateFilter(scope.minDat, scope.df) ) );
console.log("Third :" + ( reqThirdDate >= dateFilter(scope.minDat, scope.df ) ) );
console.log("Final condition: " + ( reqFirstDate >= dateFilter(scope.minDat, scope.df) && reqSecondDate >= dateFilter(scope.minDat, scope.df) && reqThirdDate >= dateFilter(scope.minDat, scope.df) ) );

Note that you don't need extra parentheses into the if expression as there is no abiguity there: >= is evaluated before &&.

You can add them if you think your code becomes more readable or you are unsure about operator precedence. I don't think this is the case here.

See Javascript Operators Precedence for a complete list of operators and their precedence.

Higher precedence means the expression part is evaluated first.


Bottom note:

As others pointed out you may take advantage of using commas , in console.log to print out values or (as in your case) labels/variable names and corresponding values.

console.log( 'label:', true );

console.log( 'a>b', a>b );

Upvotes: 1

Related Questions