Variables
- Variables are names we can use in our programs to refer to values.
- Variables are a form of abstraction. They let us write programs that can operate on different values by changing what value the variable refers to.
- We can ask what is the name of a variable and the anwswer is something like
x
or count
.
- We can also ask what is the value of a variable and the answer will be some specific value like
132
, true
, or "fruitcake"
.
Names
- Variables are written with only letters and digit characters (0-9) and must start with a letter.
- Valid variable names are things like:
x
, count
, name
, and s1
.
- Sometimes we make names out of more than one word. In that case we run the words together and capitalize the first letter of each word except the first, e.g.:
newName
, otherValue
. This is called “camel case”; the capitalized letters are like the humps of a camel.
- While string values can contain letters and digits and variable names are made up of letters and digits, they are very different things. A string is a particular value written enclosed in quotation marks and can contain almost any character including spaces and punctuation. Variable names, on the other hand, are not written in quotation marks and can contain only letters and digits. Thus
"x"
is a string value containing the single letter x while x
is a variable named x.
Declaring variables
- Variables have to be declared before they are used.
- Variables can be declared with
const
or let
.
const x = 10
declares a variable named x
with the value 10
and also says that the variable will never change value. So it is purely a name for the value.
let x = 10
declares a variable named x
with an initial value of 10
but the variable can latter be assigned a new value.
- Variables declared with
const
are called immutable meaning their value can’t change while variables declared with let
are mutable meaning they can change.
- Each variable can only be declared once in a given context. (We’ll talk later about what constitutes a context.) We can’t declare two variables with the same name because then how would we know which one we meant?
Assignment
- We assign values to mutable variables with a single equals sign:
=
. For example, x = 20
changes the value of x
from whatever it was to 20
. (This is only legal if x
was declared with let
.)
- The value of a variable is whatever value was last assigned to it.