JavaScript Variables 🤔
Tags: javascript, beginners, codenewbie
Published: 2020-07-31 12:02:58


[DCI](https://digitalcareerinstitute.org/courses) 👩🏻‍💻
<b> Variables</b> are a fundamental part of many programming languages, and are among the first and most important concepts for novice coders to learn. There are a number of different properties of variables in JavaScript, as well as several rules which must be followed when naming them. In JavaScript, there are three keywords used to declare a variable — `var`, `let`, and `const` — and each one affects how the code will interpret the variable differently.

I will cover what variables are, how to declare and name them, and also take a closer look at the difference between var, let, and const.  The effects of hoisting and the significance of global and local scope to a variable’s behavior will also be reviewed.

### What is actually a variable? 🤔

A [variable](https://developer.mozilla.org/en-US/docs/Glossary/Variable) is a named container used for storing values. A piece of information that we might reference multiple times can be stored in a variable for later use or modification. In JavaScript, the value contained inside a variable can be any JavaScript data type, including a number, string, or object.

In ES5 there was only one way to declare a variable — using the `var` keyword. As a result, most older code and learning resources will only use `var` for variables. I will point out the differences between `var`, `let`, and `const` keywords later.
### How we can use `var`?
We can use `var` to demonstrate the concept of a variable itself. In the example below, we will declare a variable, and assign a value to it.

```js
// Assign the string value Sammy to the username identifier
var username = "irie_flower";
```
The parts of this statement are:

👉 The declaration of a variable using the `var` keyword
👉 The variable name (or identifier), username
👉 The `assignment operation`, represented by the `= `syntax
👉 The `value being assigned`, "irie_flower"

🚀 Let's use username in code. JavaScript will remember that username represents the `string value 👉 irie_flower `.

```js
// Check if variable is equal to value
if (username === "irie_flower") {
  console.log(true);
}
// Output:
true
```
 Actually variables can be used to represent any JavaScript data type. In this example, we’ll declare variables with string, number, object, Boolean, and null values.

```javascript
// Assignment of various variables
var name = "Floris";
var participants = 100;
var countries = [ "England", "France", "Germany" ];
var poem = { roses: "red", violets: "blue" };
var success = true;
var nothing = null;
```
 If we want to see the value contained in a specific variable this can be done by using `console.log`.

```javascript
// Send spartans variable to the console
console.log(participants);
Output
100
```
🤔 <b> Variables</b> store data in memory which can later be accessed and modified. Variables can also be reassigned and given a new value. The simplified example below demonstrates how a password might be stored to a variable and then updated.

```javascript
// Assign value to password variable
var password = "sunflower23";

// Reassign variable value with a new value
password = "sunflower20";

console.log(password);
// output: sunflower20
```
The example illustrates a situation in which we might need to update the `value` of a variable. The value of password was `sunflower23`, but reassigned it to `sunflower20` which is the value JavaScript recognises from that point forward. But for security reasons the password can be stored in a database.

### How to name  variables ? 🤔
In JavaScript `variable` names are known as <b>`identifiers`</b>

👉 Variable names can consist only of letters `(a-z)`, numbers `(0-9)`, dollar sign symbols `($)`, and underscores `(_)`
👉 Variable names cannot contain any whitespace characters (tabs or spaces)
👉 Numbers cannot begin the name of any variable
👉 There are several reserved keywords which cannot be used as the name of a variable

JavaScript also has the convention of using camel case (sometimes stylized as camelCase) in the names of functions and variables declared with var or let. This is the practice of writing the first word lowercase, and then capitalizing the first letter of every subsequent word with no spaces between them. Most variables that are not constants will follow this convention, with some exceptions. The names of variables that are constant, declared with the const keyword, are typically written in all uppercase.
Difference Between var, let, and const
JavaScript has three different keywords to declare a variable, which adds an extra layer of intricacy to the language. The differences between the three are based on `scope`, `hoisting`, and `reassignment`.
### USAGE
<b>var</b> has:
- Function scope, hoisting, can be reassigned and declared ;
<b> let</b>
- Block scope, can be reassigned;
<b>const </b>
- Block scope 


If you are wondering which of the three you should use in your own programs. A commonly accepted practice is to use `const` as much as possible, and `let` in the case of `loops` and `reassignment`. Generally, `var` can be avoided outside of working on legacy code.

### What is a <b>Variable Scope</b>? 🤔

<b>Scope</b> in JavaScript refers to the `current context of code`, which <b>determines the accessibility of variables</b> to JavaScript. There are two types of <b>scope</b> are <b>local</b> and <b>global:</b>

Global variables are those declared outside of a block
Local variables are those declared inside of a block
In the example below, we will create a global variable.

```js
// Initialize a global variable
var creature = "fairy";
```
<b>Variables can be reassigned</b>. Using local scope, we can actually create new variables with the same name as a variable in an outer scope without changing or reassigning the original value.

In the example below, the `global variable` is `species`.
  
- Within the function is a local variable with the same name; 

- By sending them to the console, we can see how the variable’s value is different depending on the `scope`, and the <b>original value is not changed.</b>

```js
// Initialize a global variable
var species = "human";

function transform() {
  // Initialize a local, function-scoped variable
  var species = "fairy";
  console.log(species);
}

// Log the global and local variable
console.log(species);
transform();
console.log(species);

// Output : human, fairy, human
```
 In the example above, the `local variable` is <b>function-scoped.</b> Variables declared with the `var` keyword are always <b>unction-scoped</b>, meaning they recognise functions as having a separate scope. This <b>locally-scoped variable </b> is therefore not accessible from the global scope.

- The new keywords `let` and `const`, however, are <b>block-scoped.</b> This means that a new, <b>local scope </b> is created from any kind of block, including function blocks,</b> if statements, and for and `while loops`.

To illustrate the difference between `function `- and `block-scoped variables`, let's assign a new variable in an `if block` by using `let`.
```js
var dayLight = true;

// Initialize a global variable
let species = "human";

if (dayLight) {
  // Initialize a block-scoped variable
  let species = "fairy";
  console.log(`It is a day light. Morgana is currently a ${species}.`);
}

console.log(`It is not a day light.  is currently a ${species}.`);
// Output
//It is a day Light. Morgana is currently a fairy.
//It is not a day Light. Morgana is currently a human.
```
The `species` variable has one `value globally (human)`, and another `value locally (fairy)`. If we were to use `var`, however, there would be a different result.

```js
// Use var to initialize a variable
var species = "human";

if (dayLight) {
  // Attempt to create a new variable in a block
  var species = "fairy";
  console.log(`It is a day light. Morgana is currently a ${species}.`);
}

console.log(`It is not a day light. Morgana is currently a ${species}.`);

//Output
//It is a day light. Morgana is currently a fairy.
//It is not a day light. Morgana is currently a fairy.
```
In the output of this example, both the `global variable `and the `block-scoped variable` end up with the `same value`, fairy.  
- This is because instead of creating a new local variable with `var`, the same variable is reassigned in the same scope. `var` does not recognise if to be part of a different,` new scope`. It is generally recommended that you declare variables that are `block-scoped`, as they produce code that is less likely to <b>unintentionally override variable `values`</b>.