What is the difference between == and === in Dart?

It should be noted that the use of the identical function in dart has some caveats as mentioned by this github issue comment:

The specification has been updated to treat identical between doubles like this:

The identical() function is the predefined dart function that returns true iff its two arguments are either:

  • The same object.
  • Of type int and have the same numeric value.
  • Of type double, are not NaNs, and have the same numeric value.

What this entails is that even though everything in dart is an object, and f and g are different objects, the following prints true.

int f = 99;
int g = 99;
print(identical(f, g));

because ints are identical by their value, not reference.


So to answer your question, == is used to identify if two objects have the same value, but the identical is used to test for referential equality except in the case of double and int as identified by the excerpt above.

See: equality-and-relational-operators


As DART is said to be related to javascript, where the === exists, I wish not be downvoted very quickly.

Identity as a concept means that 1 equals 1, but 1.0 doesn't equal 1, nor does false equal 0, nor does "2" equal 2, even though each one evaluates to each other and 1==1.0 returns true.


Dart supports == for equality and identical(a, b) for identity. Dart no longer supports the === syntax.

Use == for equality when you want to check if too objects are "equal". You can implement the == method in your class to define what equality means. For example:

class Person {
  String ssn;
  String name;

  Person(this.ssn, this.name);

  // Define that two persons are equal if their SSNs are equal
  bool operator ==(other) {
    return (other is Person && other.ssn == ssn);
  }
}

main() {
  var bob =  Person('111', 'Bob');
  var robert =  Person('111', 'Robert');

  print(bob == robert); // true

  print(identical(bob, robert)); // false, because these are two different instances
}

Note that the semantics of a == b are:

  • If either a or b are null, return identical(a, b)
  • Otherwise, return a.==(b)

Use identical(a, b) to check if two variables reference the same instance. identical is a top-level function found in dart:core.

Tags:

Dart