# JavaScript variables

Table of content:

## What is a 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 result 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.

## How variables work in JavaScript

You create a variable by declaring it. After you declare the variable you have to assign a value to it using JavaScript assignment operator.

To declare a variable you use the var keyword which tells the browser that the text to follow is the name of a new variable. A semicolon must end the statement!

You can assign a value to your variable when you declare it or later in the script. To assign a value to your variable you use the JavaScript assignment operator equal to (=).

``` var motorbikeprice=3420; ```

The statement begins with the var keyword (which tells the browser that what follow is the name of the variable), followed by the name of the variable, the assignment operator (=) (which tells the browser to assign the value from the right of the operator to the variable from the left of the operator), and the value of the variable. The statement ends with a semicolon.

Note:
The JavaScript assignment operator (=) does not mean is equal to. The operator is equal to is two equal signs together (==).

When naming your variables you need to consider four things:

• Case sensitivity – motorbikeprice, MotorbikePrice, MOTORBIKEPRICE, and MoToRbIkEpRiCe are four different variables.
• Invalid characters – Name of a variable must begin with a letter or an underscore (_). Empty spaces are not allowed in variable names.
• Names reserved by JavaScript – There are words reserved by JavaScript and they can not be used as names of variables (See below the JavaScript reserved words).
• Meaningful and easy to remember names.

## JavaScript reserved words

JavaScript reserved words are:
abstract, as boolean, break, byte, case, catch, char, class, const, continue, debugger, default, delete, do, double, else, enum, export, extend, false, final, finally, float, for, function, goto, if, implements, import, in, instanceof, int,interface, is, long, namespace, native, new, null, package, private, protected, public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try, typeof, use, var, void, volatile, while, with.

## Variable types in JavaScript

There are four types of variables in JavaScript: number, string, Boolean, and null.

### Number variables

JavaScript does not require numbers to be declared as type of numbers (integer, decimal, etc). Numbers are just numbers!

Examples:

``` var motorbikeprice=3420; var phoneprice=89.99; var spendingprice=-250.67; var savingprice=0; var houseprice=2.50e5; ```

Notice letter e and the number 5 that follows it in the value of the variable houseprice. Number 5 is the exponent of e where e is 10. It translates into 2.50 × 105.

### String variables

String variables are variables that represent a string of text. The string of text, that represents the value of the variable, must be placed within quotation marks (single or double quotation marks are allowed) and it can contain letters, numbers, spaces or almost anything you like.

Examples:

``` var mycomputer="processor i5, 8GB of RAM"; var mymotorbike="Honda PCX"; var mydog="Flora"; ```

Note:
JavaScript strings are case sensitive.
A JavaScript string must be opened and closed with the same type of quotation marks.

#### Special characters in JavaScript

Special characters allow you to add to your string things that otherwise you could not.

Example:

``` document.write("The following folder C:\MyDocuments"); document.write("The following folder C:\\MyDocuments"); ```

The first document.write() method will not print the backslash after C: but the second document.write() method will. That is because in order to output a backslash (\) you have to use in your code a special code which in our case is double backslash (\\). You can see the list of JavaScript special characters below.

Output character Special code used
Backslash (\) \\
Double quotes (“) \”
Single quote (‘) \’
Backspace \b
Form feed \f
Newline \n
Carriage return \r
Tab \t
Vertical tab \v

If you want the output of your code to be viewed on two lines then you have to use the <br> in your code. The \n is just a new line in JavaScript not in the browser output.

#### Escaping characters

You can escape certain characters in JavaScript so they can show up correctly in the browser. Let’s say that you want the out put from a document.write() command to be “He said, “I am a web developer.””

``` document.write("He said, "I am a web developer.""); ```

The above command will cause problems in the browser. The first double quotes will make sense for the browser but when it gets to the second double quotes it thinks the string is closed now and expects the ending parenthesis and semicolon. Instead, it finds more text!

Placing a backslash in front of the quotes you want to escape tells the browser that the quotes are part of the sting avoiding errors.

``` document.write("He said, \"I am a web developer.\""); ```

In the above example, “I am a web developer.”, if single quotes would be used, then escaping them would not be necessary. Single quotes (instead of double) can be use to enclose the string but the important thing to remember is that you have to use different types of quotation marks inside the string as you use to enclose the string. If it is needed to go one level (or more) deeper with quotation marks then you have to start escaping them.

### Boolean variables

A Boolean variable is a JavaScript variable which has a value of true or false.

``` var DanWebDeveloper=true; var DanHistorian=false; ```

Notice that the values true and false are not placed between quotation marks. That is because they are recognized as Boolean values. Instead of using true or false you can use 1 for true and 0 for false.

``` var DanWebDeveloper=1; var DanHistorian=0; ```

### Null variables

A null variable is a variable that has no value.

``` var DanHistorian=null; ```

As Boolean variables, the value null of a null variable does not need to be enclosed within quotation marks since is is recognized as a JavaScript keyword with a predefined value of nothing. Null variables come in handy when you test for input in scripts.

## How to use variables in scripts?

If you just declare variables then they are not very useful. Somehow you have to use these variables to make them useful. To use a variable in JavaScript you have to make a call to it after it has been declared.

``` var DanBike="Honda PCX"; document.write(DanBike); ```

The first line declares a variable with a string value and the second line is the document.write() command that writes the value of the variable DanBike to the browser.

Let’s say that you want to add two text strings, a text string and the value of the variable DanBike, then the text string needs quotation marks around it and the operator (+) needs to be placed between the two text strings. Notice the space before the second quotation mark!

``` var DanBike="Honda PCX"; document.write("Dan has a "+DanBike); ```

You can also add the value of a variable in the middle of a string.

``` var DanBike="Honda PCX"; document.write("The "+DanBike+" is awesome."); ```

Note:
Be careful not to place the variable name withing quotation marks otherwise the browser will see it as part of the string and it will be printed as it is (instead of its value).

You can even create a variable for each piece of string you want to add then add the values of the variables.

``` var DanBike="Honda PCX"; var FirstText="The "; var LastText=" is awesome."; document.write(FirstText + DanBike + LastText); ```

Using this method gives you the possibility to change the value of a variable in order to get a different output without the need to modify the document.write() command.

Note:
You can place HTML tags within the values of your variables.

``` var DanBike="Honda PCX"; var FirstText="The "; var LastText=" is awesome."; document.write(FirstText + DanBike + LastText); ```