Imagine a container where you store a value. In programming, this kind of container is called a variable.
Computer stores data in memory cells. Each cell has its own address so the computer can access it to either store or retrieve values from it. However, the address of the memory cell is quite hard to remember for humans because it looks like this:
That’s why variables provide a way of labeling data with a descriptive name, so humans can understand it more clearly.
In short, variables (1) label and (2) store data in memory. Here are things you can do with variables:
- Create a variable with a descriptive name (label).
- Store data in a variable.
- Update data in a variable (unless it’s forbidden).
- Retrieve or reference data stored in a variable.
Remember that variables are not values. They contain values and represent them with a label.
Creating a variable
Let’s learn how to use the
const keywords to create variables.
var keyword is kept in the language for the backward compatibility with old programs but should not be used anymore.
let keyword is for creating a variable which content can vary. This is the true variable.
const keyword is for creating a variable which is actually a constant. This means that its content can’t be changed once the initial value is assigned to it.
If you’re familiar with Swift, don’t get confused now, because in Swift, the
let keyword is used for declaring constants and the
var keyword is used for declaring variables.
Let’s take a look at this example to understand what’s going on:
let myName = 'Jan';
// This will print Jan to the console
- We declared a variable (
- We gave labeled it (
- We used the assignment operator (
=) to assign it a value (
- We printed the value of the variable to the console
There are a few general rules for naming variables:
- A name cannot start with a number.
- Names are case sensitive, that means
myName is different from
myname, but it’s not a good practice to create two variables that have the same name with different cases.
- Names cannot be the same as keywords like