-3

I have this test in a JavaScript file:

if (grouping.conditional(user)) {
    console.log(grouping.conditional(user));
}

grouping.conditional looks like this:

conditional: function(user) {
    if (user.apilog[0].referer) {
        return user.apilog[0].referer.indexOf('.google.')
    } 
    else {
        return false
}

For some reason, it outputs -1 in some instances, isn't -1 false in JavaScript? In that case, how come if (grouping.conditional(user)) returns true?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Himmators
  • 13,568
  • 33
  • 122
  • 214

4 Answers4

6

The following values are falsy in JavaScript

false, 0, null, undefined, "", NaN

Everything else (including -1) is truthy.

Peter Olson
  • 131,160
  • 48
  • 197
  • 239
3

indexof() method returns the found text index. If it doesn't find anything, it returns -1.

You should change your code like this...

if (user.apilog[0].referer) {
    if (user.apilog[0].referer.indexOf('.google.') > -1)
        return  true
    else
        return false;
}
else {
    return false
}
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
2

You can test it:

if (-1) {
    console.log('true');
} 
else {
    console.log('false');
}
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
tanaydin
  • 5,002
  • 26
  • 44
1

-1 is estimated true in JavaScript.

For example:

var isTrue = -1;
if (isTrue) {
    console.log("TRUE");
}
else {
    console.log("FALSE");
}

will display TRUE.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
simopopov
  • 814
  • 5
  • 12