# Understanding Variables and Data Types in JavaScript

`var`, `let`, and `const` are three keywords you’ll encounter from the very beginning of your JavaScript journey and continue to use throughout. It’s important to understand their differences in order to write clean, reliable code. All 3 keywords are used to declare variables.

Before jumping into variables themselves, let's understand what does variable mean and why it is needed. Variables are used for storing data. And when you mature as a developer, you will realize that variables are nothing but getting a space in the memory. Primitives data are stored by value whereas non-primitive data are stored as reference (we'll learn more on data types in this article).

Var: It has functional scope. The important thing to note about var is that the values assigned can be re-assigned and same variable can be redeclared which results in lack of control over our code , resulting in bugs and other problems. Therefore in modern projects/products we rarely see the use of var. It is advisable to never use var unless dealing with legacy code.

```coffeescript
// declaration
var a;       
// redeclaration allowed
var a = 50;
console.log(a)  // 50
// reassignment is also allowed 
a = 60;
console.log(a)  // 60
```

let: It is of block-scope. Variable declared with let keyword can be reassign but can not be redeclared. let be like “ let this variable change its value but don’t let it redeclared).

```coffeescript
// declaration
let b;
// redeclaration not allowed
let b = 10;          // SyntaxError: Identifier 'b' has already been declared
// assignment allowed
b = 20;       // ✔️
// reassignment allowed
b = 30 ;        // ✔️
```

const: Now if we talk about const it is just like its name (const = constant) . It can neither be re-assigned AND redeclared once it is declared. When we declare a variable with const keyword it is mandatory to initialize it at the time of declaration.

```coffeescript
// Initialization at the time of declaration.
const c = 10
// Only declaration of const variable  is not allowed
const d;                         // ❌
// Reassignement is not allowed
c = 20                           // ❌
```

## **Important Notes About var, const and let**

1.  Aways use `let` and `const` not just over ‘var’ but never use it in the first place.
    
    *   Prefer to use `const` over `let` unless it is must that value will change.
        
    *   Using `const` and `let` gives you more control over your code.
        
2.  It is important to understand the concept of hoisting.
    
    Hoisting is the default behaviour of javascript where variable declaration are hoisted on the top.
    
    To understand it more clearly we can use an example to our cause :-
    

```coffeescript
// In case of var 
console.log(x)                  // undefined
var x = 10
```

This code is seen by javaScript in this format :

```coffeescript
var x; 
console.log(x)
x = 10;
```

So here we are accessing variable x before it is initialized resulting in undefined which is the default value for var.

Now before we jump to the `let` and `const` examples which gives us our 3rd important point, let’s discuss TDZ in 3 point.

3.  TDZ stands for Temporal Dead Zone , in this concept although `let` and `const` do get hoisted they stays in TDZ resulting in reference error.
    

```coffeescript
console.log(y)       // ReferenceError: Cannot access 'y' before initialization
let y = 10;    

console.log(z)       // ReferenceError: Cannot access 'z' before initialization 
const z = 20;
```

4.  Scope matters a lot when we deal with these 3 keyword( though not `var` , it won’t hurt to know more.)
    

```coffeescript
{
var a = 10;
let b = 20;
let c = 30;
}
console.log(a);       // 10
console.log(b);       // ReferenceError: b is not defined
console.log(c);       // ReferenceError: c is not defined
```

5.  `const` does not mean frozen value its just constant binding. In other words if we declare objects and arrays using `const` variable it does not mean that we can not change the values inside of objects and arrays. It simply means that we cannot redeclare the same variable.
    

```coffeescript
// array
const arr = [1,2,3,4,5]
arr.push(6)
console.log(arr) // 1,2,3,4,5,6

// object
const obj = { a:1, b:2, c:3 }
obj.c = 300
console.log(obj)  // { a:1, b:2, c:300 }
```

`const` stop us to reassigning the variable not from mutating the object or array.

![](https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/4839d8de-ffe3-497f-8c2a-9c9745e6f18b.png align="center")

## Primitive Data Types in JavaScript

In JavaScript, data stored in variables can belong to different data types. The simplest types of data are called primitive data types. These values are stored directly in memory and represent a single value.

JavaScript has several primitive data types, but the most common ones beginners should know are **string, number, boolean, null, and undefined**.

### 1\. String

A **string** represents text. Strings are written inside quotes.

```plaintext
let name = "Alex";
let language = 'JavaScript';

console.log(name);       // Alex
console.log(language);   // JavaScript
```

Strings are commonly used to store things like names, messages, or any textual data.

* * *

### 2\. Number

A **number** represents numeric values. In JavaScript, both integers and decimal numbers are considered numbers.

```plaintext
let age = 25;
let price = 99.99;

console.log(age);     // 25
console.log(price);   // 99.99
```

Numbers are used for calculations, counts, prices, and other numerical values.

* * *

### 3\. Boolean

A **boolean** represents a logical value that can be either **true** or **false**.

```plaintext
let isLoggedIn = true;
let hasPermission = false;

console.log(isLoggedIn);      // true
console.log(hasPermission);   // false
```

Booleans are commonly used in conditions and decision-making in programs.

* * *

### 4\. Undefined

When a variable is declared but not assigned a value, JavaScript automatically assigns it the value undefined.

```plaintext
let score;

console.log(score);   // undefined
```

This simply means that the variable exists, but no value has been given to it yet.

* * *

### 5\. Null

The **null** value represents an **intentional absence of value**. It is used when we want to explicitly indicate that a variable should contain no value.

```plaintext
let user = null;

console.log(user);   // null
```

Developers often use `null` when they want to clear a variable or indicate that data is not available yet.

## **Summary**

Writing code requires a lots of effort and knowledge therefore resulting in the need of polished knowledge. To know where and which keyword to use to store values inside variables and what will that result in gives us hold on our code. It improves code readability and maintenance.
