Comp 101 Variables: Overview

Variables

Variables allow our programs to load, store and change values in memory. 

  • Every variable has a name
  • Every variables holds a value of a specific data type

How do we use variables?

  1. Declare the variable
    1. This is where we allocate space in memory for our variable and give it a name
  2. Initialize the variable 
    1. This can be done in the same line as your variable declaration
  3. Access the variable
    1. This is where you use the value stored in the variable in your program
  4. Assign a new value to a variable
    1. You do not have to do this! You can have a variable that remains unchanged throughout your program

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

Variables and boxes

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.

mvcode.com

In this example, the variable 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 hold?
  • "1066"
  • "Harold"
  • 1485
  • true
  • 1649
  • "York"
How would you assign the values that work the the variable x?

Code tracing

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.