Search code examples
javascriptnode.jsgoogle-chromebooleanboolean-operations

Javascript Boolean Operator Confusion


I have a few lines of javascript code as below:

var str = '////';
var re = /^\/+$/g 
console.log(str && re.test(str), str && !re.test(str)); 

The output of the code in Node.js are false, false and in Chrome Client side are true, true

I'm quite confused and would anyone help to understand:

  1. Why the two boolean statements are both evaluated to true or false while they are meant to be opposite?
  2. What's difference between Chrome and Node.js in evaluating the two boolean statements?

Solution

  • From MDN (emphasis mine):

    As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match.

    So, since your regular expression is global, the following happens:

    var str = '////';
    var re = /^\/+$/g;
    
    console.log(re.test(str)); // "true" — matches and regex advances
    console.log(re.test(str)); // "false" — remainder no longer matches

    In comparison, for a non-global expression:

    var str = '////';
    var re = /^\/+$/;
    
    console.log(re.test(str)); // matches, "true"
    console.log(re.test(str)); // matches, "true"

    Note: for the code in your question, I get the same output in Node as I do in Chrome and in Firefox: true true.