What are JavaScript variables and what are they used for

What is a JavaScript variable?

A variable represents or hold a value.

Let’s consider the very commonly use example x = 2. The name of the variable would be x and its value would be 2. The value of a variable can be changed at any given time simply by giving x a new assignment. For example x = 4.

Consider the following math problem:

If x = 2, then 3 + x = ?

To solve the problem you put the value of 2 in place of variable x in the problem and you get 3 + 2 = 5. Of course, if the value of the x changes then the answer will be changed too. For x = 7 the result would be 3 + 7 = 10.

What are variable used for?

Here are the benefits of variables in JavaScript.

• Variables can be used in places where the value they represent is unknown when the code is written.
• Variables can save time in writing and updating your code.
• Variables clarify the purpose of your code.

Variables as Placeholders for Unknown Values

For example, you might have a function that takes in certain values based on user input that are unknown at the time of writing the code. In this situation a variable can be used to hold the value that will be input by the viewer, such as confirm box, input field in a form, etc.

Variables as Time-Savers

Variables can speed up script writing because their values can change. Let’s go back to our math example and consider the following problem:

If x = 2 then 3 + x - 1 + 2 - x = ?

We know that we have to substitute the value of 2 for each x so we have 3 + 2 - 1 + 2 - 2 = 4.

Let’s say that the teacher wants you to solve the same problem with a different value of x.
Solve the problem for x = 4.

Instead of re-writing the code, the value of the variable can be changed. The longer and more complex the problem gets the more useful the variable becomes.

Variables as Code Clarifiers

You can give variables meaningful names. Let’s consider the following line of code:

TotalPrice = 1560 + 1870;

These two numbers can mean anything. In this case you might want to assign 1560 as the value of a variable named PriceYamahaBike and 1870 as the name of a variable named PriceHondaBike.

TotalPrice=PriceYamahaBike+PriceHondaBike;

This is useful because instead of trying to remember what the two numbers mean you can see clearly that the script adds the price of two bikes. It is also very useful when debugging because meaningful names make easier to spot errors.