Variables are a fundamental part of programming. A variable represents some piece of data. This could be person's name, an address, a bank balance, a color, etc. One real-life analog of variables would be flashcards. On one side you have some identifier or key and on the other side you have the answer or value. The most common way of defining a variable consists of two parts which include the variable name and variable value. Look at the following example:
In the above example, we have defined a variable with an identifier of
name. This means that when we want to access this piece of information, we simply use the identifier
name. Now to give
namea value (think of flipping the flashcard over and writing something on the other side).
With some rare exceptions, the
=is almost universally used to "set" a variable to some value. In the example above, the variable
nameis set to the value of
"Mochi". And going back to our flashcard analogy, we now have a flashcard with
namewritten on one side and
"Mochi"written on the other. And now as we're writing a program, we can use
nameanytime we want to use
"Mochi". So imagine you're making a webpage and want to display the user's name, you would just reference
nameinstead of having to use
# Variable Types
In most programming languages, variables can have an implicit or explicit type. A variable's type is used to tell the program what kind of data will be stored in the variable. Let's look at some different variables types.
So these are probably the 3 most common types you should be familiar with. The first is a string which can represent anything from an individual character like
"A"to multiple characters including punctuation like
"Hello World!". Next we have numbers which can be used to store values for things like the price of an item, the number of products in stock, a bank account's balance, etc. And the last example we have is a boolean variable that can be used to track if something is
false(also can be stored as a
# Variables quiz
Okay, let's test what you just learned...
What is the output from the console.log command?
Sorry, please try again. That's correct. Let's move on to the next section.