Christopher Batts
Christopher Batts

Reputation: 123

Javascript Syntax: AngularJS Filter

I have found this excellent code for applying a filter in AngularJS here. It works as expected, although I'm a little unsure on what the shortening using ! ? and : in this context would replace.

From experience, it looks like the ? and : are a ternary operators, although I'm not entirely certain what function the ! has.

From looking around stackoverflow, it seems like the ! has multiple functions depending on context, i.e. 3755606.

 app.filter('myFilterName', function () {
    return function (value) {
        return (!value) ? '' : value.replace(/ /g, '');
    };
  });

Upvotes: 0

Views: 64

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074148

The ! is the logical NOT operator: It coerces its argument to a boolean value, then inverts that value (e.g., true becomes false and false becomes true). if (!value) checks to see if value has a falsey value. What's a "falsey" value? Any value that becomes false when coerced to a boolean. That's null, undefined, "", NaN, 0, and of course, false.

The test ? one_thing : another_thing is the conditional operator. If the value that is being tested is truthy, the expression after the ? is evaluated and the conditional expression takes that result; if not, the expression after the : is evaluated and the conditional expression takes that result. (You'll sometimes hear the conditional operator called the "ternary" operator. It's true that it's a ternary operator [an operator that accepts three operands], and it's the only ternary operator currently in JavaScript, but its proper name is the 'conditional operator'. In theory, someday other ternary operators could be added to the language...)

So the net result of:

return (!value) ? '' : value.replace(/ /g, '');

is:

  • Coerce value to boolean: Falsey values become false, all other values become true.

  • Invert that boolean.

  • If the inverted boolean is true, return ''; otherwise, evaluate value.replace(/ /g, '') and return the result.

My guess is that value is always a string. If so, then the short version is: If value is "", return ""; otherwise, return the contents of value with all spaces removed.


Side note: the () around !value are completely unnecessary.

Upvotes: 2

Related Questions