user1460015
user1460015

Reputation: 2003

Angularjs and Number.NaN

I was going through the angular docs when I ran into this:

https://github.com/angular/angular.js/blob/master/src/ng/directive/input.js#L1556

Notice that this.$viewValue = Number.NaN;

Not just in this doc but in other angular docs as well.

What is the advantage/disadvantage of doing it this way vs. just setting it as undefined or null?

Upvotes: 8

Views: 9612

Answers (2)

Dave Alperovich
Dave Alperovich

Reputation: 32500

In AgularJS specific terms:

$viewValue

Actual string value in the view.

$modelValue

The value in the model, that the control is bound to.

So, if you have an input, the value within it is in the form of a string. If you display model value or interpolated value as markup, {{ myInt }} or {{ 5 + 5 }}, it will be displayed as string.

This is because HTML is a language of text, while JS is a language of functions and values. So, to handle this dual mode for double binding, AngularJS uses $viewValue service for the "display" value of a model field and uses the $modelValue to track the "actual" value.

The "display" value should never "undefined", because interpolation of an undefined model should not raise an error. and the "display" value should never be a number. So, before it is a formal string (interpolation of $modelValue), it is a NaN.

Upvotes: 5

juvian
juvian

Reputation: 16068

My guess would be that they use Nan because, according to Section 4.3.23 of ECMAScript Language Specification NaN is defined as:

number value that is a IEEE 754 “Not-a-Number” value

So it's a number and not something undefined or null. The value is explained further in Section 8.3

Equality comparisons with NaN are defined in Section 11.9.3:

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows: If Type(x) is Number, then:

If x is NaN, return false.

If y is NaN, return false.

So For the purpose of comparison , isNaN() should be used instead:

isNaN(NaN)
// true

Upvotes: 3

Related Questions