-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,738
  • 21
  • 105
  • 131
Himmators
  • 14,278
  • 36
  • 132
  • 223

4 Answers4

6

The following values are falsy in JavaScript

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

Everything else (including -1) is truthy.

Peter Olson
  • 139,199
  • 49
  • 202
  • 242
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,738
  • 21
  • 105
  • 131
2

You can test it:

if (-1) {
    console.log('true');
} 
else {
    console.log('false');
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tanaydin
  • 5,171
  • 28
  • 45
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,738
  • 21
  • 105
  • 131
simopopov
  • 854
  • 5
  • 12