-2

I have an if-else within my main controller:

var entity = shareDataService.getModalEntity();

if (entity = "NULL" || entity.length === 1) {
    myDataPromise = getDataService.getDataFromREST(security);
    console.log("HERE")
} else {
    myDataPromise = $q.all(getDataService.keepICorrect(security));
    console.log("THERE")
};

It takes entities data from a service, shareDataService.

It works fine when entity.length === 1 or entity === "NULL", but when the array is of length 2 or more, the condition does not pass it to the else. I cannot work out for the life of my why, I have debugged just before the if-else to check the value passed to the controller's function, and the array is definitely of length 2+ when I intend it to be. Also debugging entity.length just before the if-else shows the correct length of the array. What am I missing?

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
notAChance
  • 1,360
  • 4
  • 15
  • 47
  • 2
    typo ! entity == "NULL" – David Vega Dec 03 '15 at 10:41
  • 1
    Possible duplicate of [What is the correct way to check for string equality in JavaScript?](http://stackoverflow.com/questions/3586775/what-is-the-correct-way-to-check-for-string-equality-in-javascript) – notAChance Dec 23 '15 at 15:02

2 Answers2

9

You are assigning values intead of comparing

entity = "NULL"

Try like this

entity == "NULL"

Sugession :

You can check falsy .

null,'',undefined,0,NaN consider falsy in javascript

Try like this

if(!entity || entity.length === 1)
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
1
var entity = shareDataService.getModalEntity();

if (entity = "NULL" || entity.length === 1) {

Note the = instead of == or ===, you're assigning a value of "null" to entity which then evaluates to a truthy value, the || is short-circuiting so because the first expression evaluates to truthy the length === 1 part won't be evaluated, so the true branch of the if statement will always be executed.

Dai
  • 141,631
  • 28
  • 261
  • 374