# 01 Understanding Variables and Data Types in JavaScript


Hey readers, welcome to the first blog of the JS series , in this blog we are going to discuss about ht variables and datatypes in the JavaScript, and also going to see some examples of scoping.

So without thinking too much let's proceed with the topics.

### What is variables?

think of it like a box , you must have seen you mom storing the matarials inside the box for example , she stores sugar inside a box and on the top of that box she labels it as a `sugar` similarly for the salt and other stuff also

![](https://cdn.hashnode.com/uploads/covers/68c6839f7c0256a7a628c551/e84cfc3b-9925-4a12-aa8a-e0a2065c0666.png align="center")

think of it like this

*   Label on the box (variable)
    
*   material inside it is the main content (datatypes)
    

Why we are giving such label to the box? the simple answer to the question is to pick the required material easily.

* * *

### Naming rules for variable

here are the rules that you have to keep in mind while declaring the variables

1.  It can contain only characters, numbers, $, and \_
    
2.  You cannot use keywords as variable names, for example: class, number, new, this etc.
    
3.  Variable names can not we start with the numbers
    
    ```javascript
    // valid variable names
    let name = "shubh"
    let $name = "shubh";
    let _db = "mydb"
    let $_items = "my items";
    
    // invalid variable names
    let 1name = "shubh" // incorrect : since starts with number
    let this = "mythis" // incorrect : since using keyword `this`
    ```
    

* * *

### How to declare a variable?

In javaScript , since it is loosely typed language , so we don't need to define any type before defining variables hence we can use `var` , `let` or `const` to declare the variable. let's understand the usecase and the difference between all these ways

**var**

*   it is an oldest way to decalre a variable in javaScript (this is how its done)
    
    ```javascript
    
    var name = "shubh"
    ```
    
    and generally not recommended to use althrough it is working perfectly but still due some issues it is not recommended.
    
*   it is a function-scopped, means whenever we are using var inside the functions then only we are able to use it properly otherwise it will be accessed globally (this is the probelm which i was talking about in 1st point). let me clear it with one example as well :
    
    ```javascript
    
    let b = 10;
    {
        let a = 20;
    }
    
    
    console.log(a); // output : 20
    ```
    
    on the above example , can you guess the output? you must be thinking it must through error since it is not in the correct scope but you are wrong it will give `20` as the output. this is the problem with `var` .
    
*   during hoisting we can access it even before declaration but the value returned by it will be `undefined`
    
*   Also there is one more problem with `var` we can literally redeclare the variable using `var`
    
    ```javascript
    
    var a = 30;
    var a = 20;
    console.log(a); // 20
    ```
    

**let**

*   it is introduced in ES6 module of javaScript, to solve the problem that are occuring due to `var`
    
    ```javascript
    let a = 20;
    
    console.log(a);
    ```
    
*   `let` is blocked scoped, so we can only access the value inside the same scope , unlike the `var`
    
*   we can not redeclare the variable using `let` .
    
*   while hoisting, the variables which are defined using `let` are not bound to the global hence we can't access the variables before declaration
    
    ```javascript
    
    console.log(a); // error : Cannot access 'a' before initialization
    
    let a = 20; 
    ```
    

**const**

*   this is also introduced in ES6 modules, and also having almost all the features of `let` the only change is it is having some rules / strictness like
    
    *   we can't change it's value
        
    *   we must have to assign value while declaring the variable, which was optional in case of `var` or `let`
        
        ```javascript
        const key = `SecuredKey`;
        
        //const myKey; this is not allowed
        ```
        

* * *

### Comparision between `var` , `let` and `const`

| **var** | **let** | **const** |
| --- | --- | --- |
| The scope of a ***var*** variable is functional or global scope. | The scope of a ***let*** variable is block scope. | The scope of a ***const*** variable is block scope. |
| It can be updated and re-declared in the same scope. | It can be updated but cannot be re-declared in the same scope. | It can neither be updated or re-declared in any scope. |
| It can be declared without initialization. | It can be declared without initialization. | It cannot be declared without initialization. |
| It can be accessed without initialization as its default value is "undefined". | It cannot be accessed without initialization otherwise it will give 'referenceError'. | It cannot be accessed without initialization, as it cannot be declared without initialization. |

* * *

### Scopes

Scope is the term which defines that where your variables can be accessed , basically it tells us about the boundary of the variable till where it can be accessed , in javaScript there are majorly 3 types of scopes:

Global scope : global scope means we are declaring the variable outside the block or function, then it is considered that you variable now having the global scope and can be accessed anywhere in the file

```javascript
let a = 20;

{
    console.log(a); //20 , here variable a is global scopped
}
```

Block scope : Block scope mean we are declaring the variable inside the block `{ }` , and that variable can only be accessed inside that block only

```javascript
{
    let z = "block scope"
    console.log(z); // valid // "block scope"
}
console.log(z); // not accessable
```

<mark class="bg-yellow-200 dark:bg-yellow-500/30">Note : if we use the var inside the block scope then it will be accessable outside also</mark>

Function scope : function scope means the variable only be accessible inside the function only.

```javascript
function sayHi(){
    let name = "shubh";
    console.log(name); // valid // shubh
    
}
console.log(name); // error accessing the element
```

Summary :

![](https://cdn.hashnode.com/uploads/covers/68c6839f7c0256a7a628c551/42859090-f869-4c0c-86bb-c2a375019ec6.png align="center")

* * *

### Datatypes in JavaScript

In javaScript , datatypes are divided into two categories : `primitive` and `non-primitive`.

1.  **primitive** : the datatypes which are already defined by the makers are known as primitive data types. there are total 7 primitive datatypes in js.
    
2.  **Non-primitive :** non- primitive means user-defined types
    

![](https://cdn.hashnode.com/uploads/covers/68c6839f7c0256a7a628c551/db5aa2ed-161e-459b-857f-548c0f4f3dda.png align="center")

let quickly go through with each type:

**Primitive**

1.  Symbol - Unique and immutable identifier
    
2.  Number - used to store the numeric values , it covers all type of numbers which includes integers, float, double , infinity, -infinity etc
    
3.  BigInt - it is use very long numbers eg : `const bigInt = 1234483792n`
    
4.  String - it is used to store the text values , eg : `const str= "shubh"`
    
5.  Boolean - it is used to store the `true` or `false`
    
6.  null - it is special data type of javaScript, which means the variable is empty, developer intentionally assign the null to the variable that till now has no data but in future will see for now it is empty , eg: `let balance = null`
    
7.  undefined - when we don't assign anything to the variable then that variable's data type is know as `undefined` , eg : `let name`
    

<mark class="bg-yellow-200 dark:bg-yellow-500/30">Note : if you want to check the type of variable in js the you can simply use the </mark> `typeof`

**non - primitive**

1.  Array - A special type of object used to store multiple values in an ordered list using indexes.
    
    ```javascript
    let marks = [90,33, 99, 100];
    ```
    
2.  Object - A collection of key–value pairs used to store related data and functions together.
    
    ```javascript
    const myDetails = {
         name : "Shubh",
         age : 22,
         city : "jalandhar",
         salary : '10Lpa'
     }
    ```
    
3.  Functions - A reusable block of code designed to perform a specific task and can be stored in variables or passed as values.
    
    ```javascript
    function addNums(x,y,z){
        return x + y + z;
    }
    ```
    

* * *

Hope you love the blog ❤️
