skip to Main Content

Is filter(x => !!x) the same as filter(x => !!x && x)? In both cases the method returns the same thing but I want to know the theories of the answer.

2

Answers


  1. Let’s run some tests and see what different values output for each of those. This will show you what happens for each value

    const values = [-1, 0, 1, 2, {a:'foo'}, null, undefined, true, false, 'true', 'false', 'foo'];
    
    let htmlStr = '';
    values.forEach(x => {
      htmlStr += `
      <tr>
        <td>${JSON.stringify(x, null, 0)}</td>
        <td><code>${JSON.stringify(!!x, null, 0)}</code></td>
        <td><code>${JSON.stringify((!!x && x), null, 0)}</code></td>
      </tr>`;
    });
    
    document.querySelector('tbody').innerHTML = htmlStr;
    table, th, td {border:1px solid #DDD; border-collapse:collapse;}
    td, th {padding: .25rem;}
    code{color: #b71313;}
    <table>
      <thead>
        <tr>
          <th>Value</th>
          <th><code>!!x</code></th>
          <th><code>!!x && x</code></th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    Login or Signup to reply.
  2. Yes, it is the same.
    According to MDN filter is A function to execute for each element in the array. It should return a truthy value to keep the element in the resulting array, and a falsy value otherwise

    "truthy" means the value is true when converted to a boolean, i.e., !!x. Otherwise is "falsy". Note that filter doesn’t change the passed value x itself.

    !!x && x evaluates to x when !!x is true, and false when !!x is false. MDN says "the operator && returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy."

    So

    filter(x=>x)
    filter(x=>!!x)
    filter(x=>!!x&&x)
    

    are all equivalent.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search