Matthew Ayers

I create my ideas with code.

2 minute read

Variables and Constants Explained

All modern computer programs will typically see some sort of data passed into it or used in its execution. If that data does not change throughout a certain part of the program, it is known as a constant. Variables, on the other hand, have the ability to change and may do so an infinite number of times while a program is running. An example of each is below.

// An example of a constant
let name = "Matthew"

// An example of a variable
var favoriteIceCream = "Chocolate Fudge Brownie"

In this example, my name is a constant because that will never change. My favorite ice cream flavor, while seemingly constant right now, can change with time as I discover new flavors in pursuit of a better flavor. If I find a new flavor that I like better than Chocolate Fudge Brownie, I can change that variable in the way shown below.

// Updating a variable to my new favorite flavor
favoriteIceCream = "Chocolate Chip Cookie Dough"

Here it can be seen that my favorite ice cream is now Chocolate Chip Cookie Dough, but the difference between the two examples is that I left out the word var. This is because my favorite ice cream flavor previously existed, and I do not need to tell the computer that my favorite ice cream flavor exists again. Using keywords like var and let are an easy way to indicate what kind of value the computer should expect. By using let for my name, I am telling the computer that this value will not change. Below is an example of what would happen by trying to change my name.

// Attempting to change my name to Nicholas
name = "Nicholas"

// Error: Cannot assign to value: 'name' is a 'let' constant

The error shown in the example is what would happen by trying to change my name in the program I’m using in this example. When a variable is updated to a new value, that is known as assignment, and since name is a constant, it cannot be updated.

Why This Matters

Upon first glance, variables and constants can seem incredibly simple to use. The simplicity of these ideas is fundamental to programming as a whole because it can introduce many more complex situations, and while the point of this explanation is not to look into those complex situations, it is something that should at least be recognized in the context of our modern society.

Without variables and constants, it would be impossible to give programs the necessary data they need to perform tasks. In the same way that life has many constants and variables affecting our decisions, programs need to use these same kinds of information to make decisions about what tasks to perform.

Feedback

If you have any feedback for this post, feel free to contact me so that I know how to improve. Your thoughts are greatly appreciated!

Tagged with: