JavaScript Lesson 3: Variables

0
18

What are Variables

Variables, when referring to computer programming, are containers that store data values. You get to decide on the variable name and the data that it holds. Some popular values are Strings and Numbers. Once you give a variable a value, you can overwrite the value with a different one! The main idea behind Variables is that you can store information to use it later.

JavaScript doesn’t require you to declare variables before using them as you do with many other programming languages. Variable Declaration is when you give a variable a value for the first time. We will talk about this in a minute.

We have seen variables in previous lessons, but let’s take another look.

There are other variables that exist in JavaScript, but at this point we will focus mainly on strings and numeric values.

Variable Declaration

In JavaScript, it is recommended to use the keyword var when you first use a variable. This isn’t required per say, but it helps to keep your code organized and with readability. Note that you would only have to declare variable the first time you use it. In programming terms, this is called initializing. Here is an example:

Multiple Declarations on a signal line

If you are declaring multiple variables for the first time on a signal line, you are required to use the var variable. Also remember when performing multiple statements on one line you need to include the semicolon (;) as well.

Naming a Variable

Variables can have short names (like a and b) or more descriptive names (like total, firstName, age, answer). In addition to that, variables can contain letters, numbers, underscores and dollar signs. There are some rules when naming a variable. We’ve listed them below:

  • Variable names must begin with a letter
  • Variable names are case sensitive (a and A are different variables)
  • Variable names can also begin with a dollar sign ($) or an underscore (_)
  • Reserved words (like JavaScript keywords) cannot be used as variable names

For more complex programs, we recommend using more descriptive variables so that you keep track of what each variable stands for. For example, you are more likely to know what the variable named age holds than a variable named c.

Assigning Values

Assigning a value to a variable is easy. To do so, use the equal sign (=) with the variable on the left of the equal sign and the value to be assigned on the right. Please note that this order can not be swapped. Check the example below:

Summary

  • Variables store data values
  • Giving a variable a value for the first time is declaring the variable.
  • Variables can be called upon at any point in a program after it has been declared

Next Lesson

Now that we have an understanding of variables we can talk about using JavaScript operators to perform arithmetic operations, assignment operations, string operations, and more!

Leave a Reply