Variables in Javascript
Tags: javascript, beginners
Published: 2022-11-06 18:39:54

**What is Variable ?**

If you wanna become a programmer, then variables will become inseparable part of your code and maybe your best friend. But what are variables? You can imagine them as a box or a bottle in which we can store different types of data, we can add different numbers, text, etc. In order to be more specific, variables act like a container for storing String, Number, Boolean, and complex data structure(Arrays, Objects) and even the entire function.

**Types**

JS is a dynamically typed language, so we generally don’t have to worry about assigning the type of data that is being stored in that variable. However, knowing the types makes debugging a lot easier. So, JS is smart enough to figure out what you have assigned to it and when you make changes it adapts accordingly(cool!!!). In most of the famous and older languages like java, c++ you have to specify what data type(Numbers, Strings, Float, Double, etc) a variable will contain. 
JavaScript defines seven built-in types:

- String ===> var name = “Jessy”
- Number ===> var age = 18
- Boolean ===> var isActive = true
- Array ===> var colors = [“blue”,”red”,"orange"]
- Objects ===> var person = { name: “jenny”, age: 25, gender:"female" }
- Undefined
- Null

**Note: All of these types except object are called “primitives”. ** Actually, you'll need to remember more primitive types in case of switching to another programming language(DON'T YOU DARE!).
Also, remember that in JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods. 

Now let’s see how we define a variable in Javascript.

There are 3 ways of declaring a Variable:

Using Var Keyword
Using Let Keyword
Using Const Keyword

**Declaring a Variable** 

```
var age;
let name;
```
To declare a variable use let or var keyword before your variable name. When we declare a variable, it is stored in the memory by Javascript engine with the default value of undefined ( if we don’t assign any value at the time of declaration). In this case, as we are only declaring them, at this moment they don’t contain any value and if you console their values, it will return undefined.

You can also declare multiple variables at the same time.

```
var age, name;
```
** Assigning a value to the Variable**
After declaring the variable, you can assign a value to it using the = operator

```
var age, name;
age = 18;
name = "Jenny";
```
Most of the time it's more comfortable to declare and assign a value at the same time

```
var age = 18;
```
The value of a above variable age can be accessed by simply calling it by its name.

```
console.log(age) //18
```
But make sure that the variable you're calling exist, because if not it'll throw an error.

`console.log(ankap) // Uncaught ReferenceError: ankap is not defined`

**Naming Variables in Javascript:**
Naming variables properly is very essential as firstly you can't name variable however you want. It's better when the name of your variable is simple and describes the object, array, string, etc or in short what information it stores. When you declare variables, there’s a bunch of different options. The style is up to you, but just to keep it simple you can start from Camel Casing.
`boolean isEven = true` 
Besides, there exist certain rules, which you can't neglect, but rather have to learn:
1) Don’t use reserved keywords of Javascript (like class, var, etc).

2) Variables are case sensitive, isActive variable is different from isactive

3) A variable name cannot begin with a number, underscore, symbols.

4) Variable Name can contain a mix of uppercase strings, lowercase strings, and numbers.

5) A variable name should always start with lowercase.

## var vs const vs let

As previously was said you can declare variable in 3 different ways:var, let, const

**var**

Oldest way of defining a variable in JS. It was king of the block for a long time, until it’s much more specific brothers came long.

- can be changed
- scoped globally or locally to an entire function regardless of block scope.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y3c5p9a4hctqpzywkyf9.png)

Var variables can be accessed before their declaration. Javascript moves all the var variables to the top of the function or global context. This is known as var hoisting.

**REDECLARATION OF VAR VARIABLES:**
var variables can be redeclared in the same scope. It will override the existing variable. Avoid using var as you might accidentally redeclare the same variable again and that will make your program behave differently as it will not show any errors if the variable name is already used.

```
var num1 = 8;
if(num1 % 2 == 0){
   var num1 = 9;//no error
   console.log(num1);//9
}
```
In the above example, we redeclare the num1 variable in the if block and it will override the existing num1 variable. This is because var variables have function scope and are available throughout the function as we discussed earlier.

**let**

can be changed.
scoped to the block.
let variables are not initialized until their definition is evaluated. If you try to access it before declaration then you will get an error.

```
console.log(num); //Uncaught ReferenceError: num is not defined
let num;
```
REDECLARATION OF LET VARIABLE:
Variables declared using let keyword cannot be redeclared within the same scope, it will give an error.

```
function printNums(){
   let number = 60;
    if(number > 0){
      let number =40;//no error because it has different scope
      console.log(number);//40
}

let number = 90;//Uncaught SyntaxError: Identifier 'number' has already been declared
console.log(number);//90
}
```
_let variables cannot be redeclared in the same scope_
The number variable inside the if block will not give any error because let variable creates a new scope inside any pair of curly braces. The number variable outside the if block gives an error because of the same scope.
**const**

cannot be changed after instantiation.
scoped to the block.

```
const pi = 3.14;
```
Declare those variables as a constant which you don't want to change in the entire program

Remember that constant variable must be initialized with some value otherwise it will give a syntax error.
`const job; //Uncaught SyntaxError: Missing initializer in const declaration`

But, this is not in the case of Objects. We can change the properties of an Object although we declare it as constant.

```
const person = {
  name:"Tom",
  age:13
}
person.name =  "Bob"// change the existing name property
```
But you cannot change the entire object that is declared constant. If you do, it will give an error.
`person = {gender: male}//Uncaught TypeError:Assignment to constant variable`
REDECLARATION OF CONSTANT:
Constants cannot change through re-assignment and cannot be re-declared in the same scope.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o7veb7mj3ill1nuiusdw.png)

**when to use let vs const**

There are two camps about how to approach when to use what.

_I don’t trust anyone_
This method says, use const first for every variable. If the need comes along that you need to change a variable after it's been declared, change it to let.

_I trust myself_
This method says, use let for everything. If the need comes along that you need to make sure a variable can't be changed, change it to const.

**Do’s and Dont’s**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s9rfd63rqwf0musjpgy5.png)

- Prefer let over var to define variables as let will keep our variables in the right scope and make our code more manageable.
- Use const to define those values which you don’t want to change in your entire application

**Summary**

- Use let and var to define variables and const to define constants.
- let and const has block scope whereas var has function scope.
- var variables are added to the global object and can be accessed using the window object but let variables are only limited to their block and cannot be accessed via a window object.
- Unlike var, let variables are not hoisted
- The properties of Constant Object can be changed

I hope, I've mentioned all the essential parts regarding variables, if not feel free to extend your knowledge more!!!