Comp 110 Variable Declaration, Initialization, and Assignment


Variables are used to store, change and access data. Each variable has its own name and holds a specific type of data.


When you declare a variable, you're stating that the identifier (the variable's name) will refer to a value of a specific data type.

let <variableName>: <type>;

Variable names have no spaces and can only use letters, numbers, and underscores.

No variable can be used before it is declared.


let myFavoriteNumber: number;

You cannot declare more than one variable with the same name within the same scope, and you cannot access a variable outside of its scope. 


When you assign a value to a variable for the first time, you are giving it an initial value. This is called initializing the variable. Here's what this looks like:

<variablename> = <value>;

The type of the value you assign to the variable must match the type you specified when you declared the variable.

Example with myFavoriteNumber:

myFavoriteNumber = 101;

Declaration and Initialization

Instead of declaring a variable then later initializing it in a separate line of code, we can do all this on the same line! Here's how:

let <variableName>: <type> = <value>;


let myFavoriteClass: string = "COMP110";


After you declare and initialize a variable, you can still change its value. All you have to do is assign a new value to that variable. When you change a variable's value, you are reassigning a new value to that variable. A variable's value is the value most recently assigned to that variable.

Example with myFavoriteNumber:

let myFavoriteNumber: number = 110; // here we are declaring an initializing
print(myFavoriteNumber); //prints 110
myFavoriteNumber = 101; // here we are reassigning the value of myFavoriteNumber
print(myFavoriteNumber); //prints 101

Putting it all together

You can access a variable's value by using the variable name.

Here are a few examples of making and using variables:

import { print } from "introcs";

let food: string; // declaration
food = "pizza"; // initialization

let numberOfSlicesLeft: number; // declaration
numberOfSlicesLeft = 8; // initialization

let isHungry: boolean = true; // declaration and initialization together

numberOfSlicesLeft = 4; // reassignment
isHungry = false; // reassignment

print(food); // prints pizza
print(isHungry); // prints false
print(numberOfSlicesLeft); // prints 4