Assignment and Declaration of Variables

College Class 8.png

When you set up a variable, you are really setting up space that is going to hold something else in it.

Think of it like a container.

🎁

You are going to use that box, or container, to put something of value in it. Whatever you put in it is going to be of value to the program and it may even change over time—you may take something out and put something else in the same container. Before you put anything in it, you have to set up the container first….that’s called declaring the variable.

In JavaScript, you use certain keywords (or reserved words) to declare a variable.

var team_1;

The reserved word, var, allows you to set up a space, if you will, in memory to store a value that will go into it and I’ve named that space, team_1.

Right now, I have just declared a variable, I haven’t stored anything, or any value, in it, yet.

The variable is not much use to me with nothing in it, but maybe I want to set it up this way, for right now, and later on I will go ahead and assign a value to it. To assign a value to it we use the =.

=

In programming, this symbol is not called an equal sign, it is an assignment operator. It assigns a value to a variable. It doesn't mean that the variable is equal to the value, but that the value has been assigned to that variable (the variable is holding that value). So, I could write:

var team_1 = “Patriots”;

Now, whenever I use the variable team_1, the word Patriots is what will be manipulated.

document.write(team_1);

The above statement would write the word, Patriots, in the document and onto the screen.

So….

var team_1 = “Patriots”;

…declares the variable team_1 and assigns the value, Patriots, to it. This is often called initializing a variable (when you assign it a value). So, think of assigning a value to a variable as holding that value in that variable and declaring a variable as setting up a spot in memory.

You can declare more than one variable on a single line:

var sum; meanNumber; firstNumber;

You can also assign values to more than one variable on a single line:

sum = 7; meanNumber = 4; firstNumber = 3;

Note: We have used a semicolon to separate each statement on a single line.

As we have mentioned, you can also declare and initialize in one line:

var sum = 7;

Now, you can also use the reserved words let and const to set up variables, but we will discuss them in a later post. For right now remember:

Declaring a variable sets up a space within which to hold a value and…assignment involves putting a value inside of that space.

Danita Smith