Variables in JavaScript
Published: 2022-11-10 18:26:27

## What are Variables?

Variables are containers for storing data (storing data values).

In this example, x, y, and z, are variables, declared with the `var` keyword:

Example

```
var x = 5;
var y = 6;
var z = x + y;
```

In this example, x, y, and z, are variables, declared with the `let` keyword:

Example

```
let x = 5;
let y = 6;
let z = x + y;
```
In this example, x, y, and z, are undeclared variables:

Example

```
x = 5;
y = 6;
z = x + y;
```
From all the examples above, you can guess:

x stores the value 5
y stores the value 6
z stores the value 11

Always declare JavaScript variables with `var`, `let`, or `const`.


**When to Use JavaScript var?**

The `var` keyword is used in all JavaScript code from 1995 to 2015.

The `let` and `const` keywords were added to JavaScript in 2015.

If you want your code to run in older browsers, you must use `var`.


**When to Use JavaScript const and let?**

If you want a general rule: always declare variables with `const`.

If you think the value of the variable can change, use `let`.

In this example, price1, price2, and total, are variables:

Example

```
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
```

The two variables price1 and price2 are declared with the `const` keyword.

These are constant values and cannot be changed.

The variable total is declared with the `let` keyword.

This is a value that can be changed.

## Just Like Algebra

Just like in algebra, variables hold values:

```
let x = 5;
let y = 6;

```
Just like in algebra, variables are used in expressions:

```
let z = x + y;
```
From the example above, you can guess that the total is calculated to be 11.

> Note
> Variables are containers for storing values.


## JavaScript Identifiers

All JavaScript variables must be identified with unique names.

These unique names are called **identifiers**.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

* Names can contain letters, digits, underscores, and dollar signs.
* Names must begin with a letter.
* Names can also begin with $ and _ (but we will not use it in this tutorial).
* Names are case sensitive (y and Y are different variables).
* Reserved words (like JavaScript keywords) cannot be used as names.

> Note
> JavaScript identifiers are case-sensitive.

## The Assignment Operator

In JavaScript, the equal sign `=` is an "assignment" operator, not an "equal to" operator.

This is different from algebra. The following does not make sense in algebra:

x = x + 5

In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.

(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)

> Note
> The "equal to" operator is written like == in JavaScript.

## JavaScript Data Types

JavaScript variables can hold numbers like 100 and text values like "John Doe".

In programming, text values are called **text strings**.

JavaScript can handle many types of data, but for now, just think of numbers and strings.

=> Strings are written inside double or single quotes. Numbers are written without quotes.

If you put a number in quotes, it will be treated as a text string.

Example

```
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';
```

## Declaring a JavaScript Variable

Creating a variable in JavaScript is called "declaring" a variable.

You declare a JavaScript variable with the `var` or the `let` keyword:

```
var carName;
```
or:

```
let carName;
```

After the declaration, the variable has no value (technically it is `undefined`).

To assign a value to the variable, use the equal sign:

```
carName = "Volvo";
```

You can also assign a value to the variable when you declare it:

```
let carName = "Volvo";
```

In the example below, we create a variable called `carName` and assign the value "Volvo" to it.

Then we "output" the value inside an HTML paragraph with id="demo":

Example

```
<p id="demo"></p>

<script>
let carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
```

> Note
> It's a good programming practice to declare all variables at the beginning of a script.

## One Statement, Many Variables

You can declare many variables in one statement.

Start the statement with `let` and separate the variables by comma:

Example

```
let person = "John Doe", carName = "Volvo", price = 200;
```

A declaration can span multiple lines:

Example

```
let person = "John Doe",
carName = "Volvo",
price = 200;
Value = undefined
```

In computer programs, variables are often declared without a value. The value can be something that has to be calculated or something that will be provided later, like user input.

A variable declared without a value will have the value `undefined`.

The variable `carName` will have the value undefined after the execution of this statement:

Example

```
let carName;
```

## Re-Declaring JavaScript Variables

If you re-declare a JavaScript variable declared with `var`, it will not lose its value.

The variable `carName` will still have the value "Volvo" after the execution of these statements:

Example

```
var carName = "Volvo";
var carName;
```

> Note
> You cannot re-declare a variable declared with `let` or `const`.

This will not work:

```
let carName = "Volvo";
let carName;
```

## JavaScript Arithmetic

As with algebra, you can do arithmetic with JavaScript variables, using operators like `=` and `+`:

Example

```
let x = 5 + 2 + 3;
```

You can also add strings, but strings will be concatenated:

Example

```
let x = "John" + " " + "Doe";
```
Also try this:

Example

```
let x = "5" + 2 + 3;
```

> Note
> If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.

Now try this:

Example

```
let x = 2 + 3 + "5";
```

## JavaScript Dollar Sign $

Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names:

Example

```
let $ = "Hello World";
let $$$ = 2;
let $myMoney = 5;
```

Using the dollar sign is not very common in JavaScript, but professional programmers often use it as an alias for the main function in a JavaScript library.

In the JavaScript library jQuery, for instance, the main function $ is used to select HTML elements. In jQuery $("p"); means "select all p elements".

## JavaScript Underscore (_)

Since JavaScript treats underscore as a letter, identifiers containing _ are valid variable names:

Example

```
let _lastName = "Johnson";
let _x = 2;
let _100 = 5;
```

Using the underscore is not very common in JavaScript, but a convention among professional programmers is to use it as an alias for "private (hidden)" variables.


## JavaScript Scope

Scope determines the accessibility (visibility) of variables.

JavaScript has 3 types of scope:

- Block scope
- Function scope
- Global scope


## Block Scope

`let` and `const` provide Block Scope in JavaScript.

Variables declared inside a `{ }` block cannot be accessed from outside the block:

Example

```
{
  let x = 2;
}
// x can NOT be used here
```

Variables declared with the var keyword can NOT have block scope.

Variables declared inside a `{ }` block can be accessed from outside the block.

Example

```
{
  var x = 2;
}
// x CAN be used here
```


## Local Scope

Variables declared within a JavaScript function, become LOCAL to the function.

Example

```
// code here can NOT use carName

function myFunction() {
  let carName = "Volvo";
  // code here CAN use carName
}

// code here can NOT use carName
```

Local variables have Function Scope:

They can only be accessed from within the function.

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is completed.


## Function Scope

JavaScript has function scope: Each function creates a new scope.

Variables defined inside a function are not accessible (visible) from outside the function.

Variables declared with `var`, `let` and `const` are quite similar when declared inside a function.

They all have Function Scope:

```
function myFunction() {
  var carName = "Volvo";   // Function Scope
}
```

```
function myFunction() {
  let carName = "Volvo";   // Function Scope
}
```

```
function myFunction() {
  const carName = "Volvo";   // Function Scope
}
```


## Global JavaScript Variables

A variable declared outside a function, becomes GLOBAL.

Example

```
let carName = "Volvo";
// code here can use carName

function myFunction() {
// code here can also use carName
}
```

A global variable has Global Scope:

All scripts and functions on a web page can access it. 


## Global Scope

Variables declared Globally (outside any function) have Global Scope.

Global variables can be accessed from anywhere in a JavaScript program.

Variables declared with var, let and const are quite similar when declared outside a block.

They all have Global Scope:

```
var x = 2;       // Global scope
let x = 2;       // Global scope
const x = 2;       // Global scope
```

##  Points to Remember

- Variable stores data value that can be changed later on.
- Variables can be defined using var keyword. Variables defined without var keyword become global variables.
- Variables must be initialized before accessing it.
- JavaScript allows multiple white spaces and line breaks in a variable declaration.
- Multiple variables can be defined in a single line separated by a comma.
- JavaScript is a loosely-typed language, so a variable can store any type value.
- Variable names are case-sensitive.
- Variable names can contain letters, digits, or the symbols $ and _. It cannot start with a digit 0 - 9.
- Variables can have local or global scope. Local variables cannot be accessed out of the function where they are declared, whereas the global variables can be accessed from anywhere.