Laziale
Laziale

Reputation: 8225

if else statement in JavaScript not working properly

As you can see from this code:

function setBodyClasses() {
    var answer = $surveyAns.getAnswer('QUEST223');
    answer = 'oro';
    if(!surveyUtils.isNullOrWhiteSpace(answer)) {
        if (answer.toLowerCase().indexOf('oro')) {
            $scope.bodyClasses = 'vip_gold';
        }
        else if (answer.toLowerCase().indexOf('platino')) {
            $scope.bodyClasses = 'vip_platinum';
        }
        else {
            $scope.bodyClasses = '';
        }
    }
}

For some reason the if else statement is not working correctly, as you can see the answer value is oro and it should stop on the first if, but when its on the first if condition it compares the value and it moves forward assuming that is not the same value, and for some other reason it enters the second if condition even though the value is different. Any idea why this is happening?

Upvotes: 0

Views: 120

Answers (3)

gen_Eric
gen_Eric

Reputation: 227240

You are incorrectly checking if answer contains the string. .indexOf() will return you where in the string it is. It could be 0, that's the start of the string (it's like an array, where it's zero-indexed). It returns -1 if it's not found.

If you just do if(answer.toLowerCase().indexOf('oro')) it will be false, since 0 is "falsly".

You want to do: if(answer.toLowerCase().indexOf('oro') >= 0).

Are you sure you want to use indexOf() in the first place? This is checking if the string "contains" oro. Are you sure you don't just need: if(answer.toLowerCase() === 'oro')?

Upvotes: 4

Vardarac
Vardarac

Reputation: 563

You are using indexOf to find the existence of "oro" in your string. IndexOf, however, correctly returns a value of 0, which equates to false in JavaScript. I personally would use answer.indexOf('oro') !== -1.

Upvotes: 1

juvian
juvian

Reputation: 16068

indexOf is returning 0, and 0 is a falsy value so its not entering the condition. Should be:

.indexOf('oro') > -1

Same with the other conditions

Upvotes: 2

Related Questions