I'm working on an AngularJS project. I noticed that the following expression returns a number.
In the view, {{undefined + 10}}
will output 10.
In JavaScript, undefined + 10
will output NaN.
Why is this behavior different in a view?
A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .
The Boolean value of undefined is false.
A variable or an object has an undefined value when no value is assigned before using it. So you can say that undefined means lack of value or unknown value.
A function is undefined when the denominator is equal to zero. If there are variables in the denominator, the point at which the expression in the denominator is zero is the point where that function is undefined.
That's the advantage of interpolation.
Interpolation markup with embedded expressions is used by AngularJS to provide data-binding to text nodes and attribute values.
If the interpolated value is not a String, it is computed as follows:
$interpolate
looks for a custom toString()
function on the object, and uses that.JSON.stringify
is used.During runtime the compiler uses the $interpolate
service to see if text nodes and element attributes contain interpolation markup with embedded expressions.
Also, the angular compiler use an interpolateDirective
and registers watchers in order to listen for model changes. That's the process of digest cycle.
Read more here to understand how interpolation works.
Why
{{'' == +Infinity}}
returns true ?
In AngularJS, $interpolate
service evaluates +Infinity
to 0
value.
angular.module('app', []) .controller('Controller', ['$injector', function($injector) { }]); setTimeout(function() { angular.bootstrap(document.getElementById('body'), ['app']); });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script> <div id="body"> <div ng-controller="Controller"> {{+Infinity}} </div> </div>
Now the expression remain {{0==''}}
.
Why 0==''
is evaluated to true
?
The left side is of type Number
. The right side is of type String
.
In this case, the right operand is coerced to the type Number:
0 == Number('') => 0 == 0,
which is evaluated to true
boolean value.
Here is applied The Abstract Equality Comparison Algorithm.
If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With