Arvind Kumar
Arvind Kumar

Reputation: 973

Why "var" instead of data type is considered a better practice in Dart?

I was studying Dart and it is mentioned in the tutorial that when you are initializing the variable, use the keyword "var" instead of the type of data like "int". Dart will automatically infer that it is an "int" or "String" based on the initial value. But will it not be faster if we tell the dart directly that it is going to an "int". Dart is strongly typed and we cannot use the same variable for an integer and string like "javascript", then what is the purpose of "var" in dart context. It seems to me that using data type will be faster and easier. Why it is considered a better practice to use the "var"?

Upvotes: 21

Views: 5294

Answers (2)

Acid Coder
Acid Coder

Reputation: 2746

the reason I think var is better is that it is slightly more convenience, for example

var n = 1;
int m = 1;

both n and m are integer

if some day you changed your mind and want to reinitialize them with new decimal number instead

var n = 9.9;
double m = 9.9;

in this case, var requires less typing and still able to infer the type correctly

Upvotes: 1

user15782390
user15782390

Reputation:

A variable of type dynamic would be similar to javascript where it can change type during runtime. For example store an integer then change to a string.

var is not the same as dynamic. var is an easy way to initialise variables as you don't have to explicitly state the type. Dart just infers the type to make it easier for you. If you write int number = 5 it would be the same as var number = 5 as dart would infer that this variable is an integer.

The reason the tutorial might have said that var is better than int may be convention to make the code more readable but I believe it doesn't have any impact on your code. You can use either and it won't make a difference.

Upvotes: 10

Related Questions