3
votes

I just started learning about Dart.

Before Dart, I have worked with Javascript and have some experience.

Now, as I was going through the documentation from Tutorial Point. They have mentioned something like this

All variables in dart store a reference to the value rather than containing the value. The variable called name contains a reference to a String object with a value of “Smith”.

In Javascript, I guess array and objects are reference type.

Meaning, If we do something like this

[Update:] This code snippet is incorrect

let a = ["Apple", "orange"]

let b = a 

a = ["Bananna"] 

console.log(b) //["Bananna"]

but that is probably only for object and array in JS (and not for const and let)

let a = 5
let b = a 
a = 7
console.log(b) //5 

From the quote,

All variables in dart store a reference to the value

[Question:] Does this mean that even things like int, string.. and every variable we create in Dart is reference? and the equivalence of above code will print 7 in Dart or I am getting something wrong (in general)?

let a = 5
let b = a 
a = 7
console.log(b) //7
1
Your example with ["Apple", "orange"] and then reassigning to ["Banana"] is not how javascript behaves. In that case ["Apple", "Orange"] would be logged to the console. - Nate Bosch

1 Answers

8
votes

Everything is an Object in Dart. Some objects are mutable - that is they can be modified, and some are immutable, that is they will always be the same value.

When you assign with var b = a; both b and a will reference the same Object, but there is no further association between the names b and a. If you mutate that Object by calling methods on it or assigning to fields on it (things like List.add for example) then you will be able to observe the mutated Object through either name b or a. If you assign to a then the variable b is unaffected. This is true in javascript as well.

The reason some types, like numbers or Strings, appear special is that they cannot be mutated, so the only way to "change" a is to reassign it, which won't impact b. Other types, like collections, are mutable and so a.add("Banana") would be a mutation visible through either variable referencing that list.

For example, with assignment:

var a = ['Apple', 'Orange'];
var b = a;
a = ['Banana']; // Assignment, no impact to b
print(a); // [Banana]
print(b); // [Apple, Orange]

With mutation:

var a = ['Apple', 'Orange'];
var b = a;
a.clear(); // Mutation, the _list instance_ is changed
a.add('Banana')  // Another mutation
print(a); // [Banana]
print(b); // [Banana]