Understanding Variables and Constants in Dart

Topic Overview and Goal Setting

Welcome back! As we continue our Dart Decoding Adventure, we're preparing to gain a better understanding of Dart Variables, our cornerstone concepts. Like bricks in a building, variables form the base of our code, enriching it with data and authenticity.

Essentially, a variable in coding is much like a container — it's a specific spot in memory where a value can be held. This lesson aims to demystify the concept of Dart variables, delving into their definition, the naming conventions, value assignments, and thoughts on immutable variables.

What are Dart Variables?

Visualize Dart variables as small containers packed with data. The brief example below highlights how a variable is created in Dart:

int numberOfPlanets; // We declare a variable, akin to choosing a container
numberOfPlanets = 8; // We then fill it with a value
print(numberOfPlanets); // Finally, we validate its contents. It outputs: 8

Here, int depicts the variable's data type (integer number), numberOfPlanets is the variable's identifier, and 8 is its value. We'll touch upon data types in our next lesson, so relax if the int part isn't clear as of now.

However, you can also declare and assign a value to a variable in a more succinct manner. Here's an example:

int numberOfPlanets = 8; // Declaring and assigning the variable with a value at the same time
print(numberOfPlanets);

Dart Naming Conventions

Naming a Dart variable requires adherence to certain rules and conventions, much like correctly labeling a container. These ensure that your code avoids errors and remains interpretable to others.

The variable name should begin with a lowercase alphabet following the CamelCase notation: if the variable name has just one word, it should be entirely lowercase; for variable names with multiple words though, the first one should be lowercase, and the remaining ones should begin with a capital letter. Examples include age, weight, myAge, firstDayOfWeek.

Character such as digits and special symbols cannot be the leaders in variable names.

// Appropriate variable naming
int myAge = 24;
int myWeight = 65;
int area51Population = 0;

// Incorrect variable naming (commented intentionally)
// int 0zero = 0;
// int ~tildeMark = 1;

Assignment Operations in Dart

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal