Do angular conditions work the same way as pure javascript?

776 views Asked by At

I wonder if there is the same difference between identity === and equality == operators in angular directives like in pure javascript?

For example is

ng-if="value === 'foo'

better than

ng-if="value == 'foo'

What I checked is that

ng-if="true == 1

passes but

ng-if="true === 1

doesn't, so it looks like it works the same way like pure js. On the other hand in angular source they use just equality check, even tho in js identity is preferred.

https://github.com/angular/angular.js/search?utf8=%E2%9C%93&q=ng-if

Which operator should we use in angular directives?

EDIT: To clarify - I'm not asking about javascript conditions, this has been already answered on stack, my question is - is there any difference in conditions between pure js and angular directive conditions?

1

There are 1 answers

0
sam100rav On

Main difference between "==" and "===" operator is that former compares variable by making type correction e.g. if you compare a number with a string with numeric literal, == allows that, but === doesn't allow that, because it not only checks the value but also type of two variable, if two variables are not of same type "===" return false, while "==" return true.

Since JavaScript support both strict equality and type-converting equality, it's important to know which operator is used for which operation. As I said that, === takes type of variable in consideration, while == make type correction based upon values of variables, following are couple of more differences between "==" and "===" operator in JavaScript programming language :

1) When we compare two variables of different type e.g. a boolean with a string or a number with String using == operator, it automatically converts one type into another and return value based upon content equality, while === operator is strict equality operator in Java, and only return true if both variable of same type and also contains same value. This will be much clear with following example of == and === operator in JavaScript :

0==false   // true, because false is equivalent of 0
0===false  // false, because both operands are of different type
2=="2"     // true, auto type coercion, string converted into number
2==="2"    // false, since both operands are not of same type

2) "==" operator is known as type coercion operator and anytime if both values are same and compared using ==operator, type coercion happens. On the other hand === is known as strictly equality operator. It's much similar Java's equality operator (==), which gives compilation error if you compare two variables, whose types are not compatible to each other. In fact, you should always use "===" operator for comparing variables or just for any comparison.