i-am-niall
i-am-niall

Reputation: 170

Explain how this function removes the negative values

function bouncer(arr) {
  // Don't show a false ID to this bouncer.

  for (var i = 0; i < arr.length; i++) {
        if (!arr[i]) {
            arr.splice(i, 1);
            i = i-1;
        }
    }
    return arr;

}

bouncer([7, "ate", "", false, 9]);

I don't understand how the exclamation mark works in the conditional. I know it's used to negate but I'm not understanding how.

Upvotes: 2

Views: 62

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138477

if (!arr[i]) {

Means basically if not arr[i]. This works as values in js are either truthy or falsy, so just falsy values would pass the upper condition (if not falsy === true):

null,undefined,"",0,false

Upvotes: 5

Related Questions