Variables allow our programs to load, store and change values in memory.
let x: number; // declaration x = 42; // initialization let y = 36; // declaration and initialization y = x + 3; // here, we are accessing x and assigning a new value to y
Another way to think of a variable is like a box. The box has a name (this is the name of your variable) and contains a value of a specific type.
In this example, the variable x is a box that holds a number value. Here, the value it holds is 42.
When we declare a variable, we are creating and naming this box, which in our code is simply a space in memory to hold a value. We cannot use the variable before we declare it, just like we cannot use a box before we create it!
When we initialize our variable, we are putting a value inside our box for the first time.
When we access our variable, we are using the value inside the box.
Finally, when we assign our variable, we are changing the value inside the box.
In the example above, which values could the variable x hold?
How would you assign the values that work the the variable x?
What would be the value of the variables x and y after this code runs?
let x: number; let y = 110; x = 101; y = x + y; x = y;
Answer: y = 211 x = 211
Which option, 1 or 2, would cause an error, and why?
let greeting: string; greeting = hello; // option 1 greeting = "800"; // option 2
Answer: Option 1 would cause an error because hello without quotes is not considered a string by the computer and therefore cannot be assigned to greeting which must be a string since it was declared as such.