JavaScript : Variables and Constants (A beginner's Perspective)
Tags: javascript, beginners, tutorial, programming
Published: 2022-12-01 19:37:47

In this article, I've attempted to do a complete breakdown on the concepts of variables and constants as I've learned about them. I hope it helps!

Quick Disclaimer! I am also a beginner trying to navigate my way through programming and writing on the knowledge I gain is my way of learning. So bear with me if I'm not completely accurate or clear.

---
## Variables
**Variables** are like containers for storing values. They are very important in how easily information is stored and passed in our program as we'll find out in progression.

## Declaring Variable
Keywords: Variables are _declared_ using three keywords in javascript. _Declaring_ is you giving JavaScript an order to create a variable. These keywords include `var`, `let`, `const`. 
An example,
First declare a variable
```javascript
var firstName;
let firstName;
```
Then you assign(store) a value to it
```javascript
firstName = 3;
```
Then you can refactor your code which is declaring a variable and assigning a value to it in the same line of code. This is called **Explicit initialization**. This is the only way to declare `const` variables.

```javascript
var firstName = 3;
```

```javascript
let firstName = 3;
```

```javascript
const firstName = 3;
```



## Redeclaration
Although it only applies to the `var` keyword, you can redeclare variable using the `var` keyword.

```javascript
var firstName = "my name";
var firstName = "your name";
```

## Reassignment
You can change the value assigned to your variable by assigning a new value to the variable. It applies to `var`and `let` keywords.

```javascript
var firstName = 3;
firstName = 5;
console.log(firstName); // 5
```
You cannot reassign a new value to a constant variable.

```javascript
const firstName = "My Name";
firstName = "Your Name"; //Uncaught TypeError: Assignment to constant variable.
```
But there is a little twist to this rule, so when constant variables are assigned to object data types(i.e name:value pairs), the variable assignment(values) are _references_ containing the object values. Let's take a look at this illustration for clearer understanding

```javascript
const objectName = { a : 5};
```
`{ a : 5}` - The curly braces represents the whole object as a reference to the variable `objectName`. Now,the reference can  cannot be changed in respect to the variable but the object value  can be changed.

```javascript
const objectName = { a : 5};

//Attempting to reassign a new value to the variable reference
objectName = { a : 3}; //Uncaught TypeError: Assignment to constant variable.
```

But we can reassign a new value to the object reference.

```javascript
objectName.a = 3;
console.log(objectName); // { a : 3}
```

## Scopes
This process of declaring variables using the `var` keyword also works with the `let` keyword. But it is recommended to use  `let` rather than `var` because `let` allows you declare variables that are limited to a **Block scope**, unlike `var` which declares a variable globally to an entire function, regardless of the block scope. 

For better understanding, let's get a clear picture of what these scopes mean.

**Scope** tells us which variable is accessible and unto what point it is accessible. We can identify scopes by curly braces `{}`. Let's look at the different scopes we have in javascript.

**Global Scope**: This is your entire javascript code file and all other scopes, functions and variables are contained in the global scopes.

**Local Scope**: These are variables declared in the functions and are further classed into **function scopes** and **block scopes**.

- **Function Scope**: These are variables declared inside a function and they can only be accessed within the function.

- **Block scope**:These variables are only accessible within the particular loop or conditional statements they are declared in.

To illustrate these concepts, let's create the following program
(`const`variables are equally block-scoped, so we'll be using only `var`and `let` keywords for easier understanding):

```javascript
function x() {
If (true) {
var a = 1;
let b = 2;
console.log (a);// 1
console.log(b);//2
         }
}
x();
```
Both declarations are executed because they are within a block scope. Now let's see what happens when we declare a variable within a block scope and print outside the block scope.

```javascript
function x() {
if (true) {
var a = 1;
let b = 2;
}
console.log(a); // 1
console.log(b); // Uncaught ReferenceError: b is not defined
}
x();
```
Here we can see that the variable declared with the `let` keyword is not recognised outside the block scope of the `if` statement. `var` functions regardless of what scope it has been declared in. Let's take a look at how this can be a disadvantage.

```javascript
function x() {
var a = "a"; // very important variable
let b = "b";
 if(true) {
var a = 1;
let b = 2;
}
console.log(a); // 1
console.log(b); // b
}
x();
```
The result we get here is `b -> b` because that is the value of `b` in the function scope (the variable `b` in the block scope has been terminated within the scope).

we get `a -> 1` being our output for `var` keyword because `var` is not dependent on the scope it is declared in and therefore it will override an existing variable(our important variable) and print out the most recent variable declared using `var` keyword. This can cause bugs in our code hence, it is safer to use the `let` keyword which is terminated within it's scope.

## Hoisting
Hoisting is a concept where variables and function declarations are moved to the top of their scope before the execution of the code. while `var` can be hoisted to the top before declaration, `let`and `const`cannot because only the `var`keyword is initialized as `undefined`.
```javascript
console.log(firstName);
var firstname = "my name";
```

## Quick summary
Incase the differences weren't clear enough, here's a summary
1.  `var` and `let` both can be declared without initializing while `const` must be declared and assigned a value on the same line of code.

2. `var` and `let` variables can be reassigned to new values while you cannot reassign new references for `const` variables.

3. `var` can be redeclared while both `let` and `const` cannot be redeclared.

4. `let` and `const` are block-scoped while `var` is global-scoped and function-scoped when declared in a function.

5. `var` can be hoisted to the top of the code block, `let` and `const` cannot.


You can check out these resources for further and  in-depth understanding of these concepts.
https://medium.com/nerd-for-tech/function-scope-block-scope-in-js-d29c8e7cd216
https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/
https://www.youtube.com/watch?v=FNh2JCiFXIg

---
Thank you so much for reading❤. Comments, questions and contributions are welcome.

I hope this article breaks down the concepts of defining variables in a clear, concise manner. 
Also, please I need help with embedding resources! Please somebody, help!🤧