Variables
This section will teach you to store data in your programs so that they can be retrieved and used later.
Last updated
This section will teach you to store data in your programs so that they can be retrieved and used later.
Last updated
If you don't know how data types work in Sonar, please visit the section first.
When we create programs, we will usually want to store some kind of data so that we can use it at some later point in our program. For example, if we were writing a phonebook, we would want to be able to save the names and phone numbers of our contacts.
In Sonar, we can save our data by using variables.
A variable can be defined as a temporary location for storing data in our programs. Variables are temporary because they don't save their data forever. Instead, they keep data for as long as it takes our programs to end. This way, we can use our data while our program is doing work, but as soon as our program's work is finished, our data (which will no longer be needed now) will be automatically erased from the computer. The computer does this so that it will always have enough space in its memory to do other things (like playing music, streaming Netflix or running your own programs).
In Sonar, it is very easy to create variables. Variables are created using the let keyword.
A "keyword" is a special word that has special meaning in Sonar. Keywords are often used to perform very important functions that make it possible for our programs to work.
To create a variable, you need three things:
The let keyword
A name for your variable
An equals symbol, followed by the data to store in your variable
For example:
This will create a variable in your program called "name". Your new name variable will contain the data "Cinderella".
We can use this variable in our program simply by writing its name:
Variables can be used to store all kinds of data:
And variables that hold data can be used directly in programs:
is equivalent to:
Variables and their data are always interchangeable.
The process of creating a variable is called "variable declaration".
After a variable has been created (or "declared"), it can be re-assigned. This means that its value can be changed to a different one. To re-assign a variable, simply write the name of the variable, followed by an equals (=) symbol, and the value you want to assign to the variable.
A variable that has not been declared cannot be assigned to or used.
Imagine you need have a variable that has a value of 1, and you need to add 2 to it, you might write:
Unlike many programming languages, Sonar allows you to use a simpler, faster variable assignment syntax to obtain the same effect:
This will add 2 to the original value of number
(1), and assigns the result back to number
.
There are four double-operator assignment operators:
+=
variable += 1
variable = variable + 1
-=
variable -= 1
variable = variable - 1
*=
variable *= 1
variable = variable * 1
/=
variable /= 1
variable = variable / 1