# Understanding of data type in Javascript

Today, we are going to deep dive into the datatypes and types of variable in javascript.

### var

In javascript, **var** is keywords which help in declaring the variable in javascript and help in declaring function scope as well as global scope.

```javascript
var name = "Javascript"
var developed_In = 1995
var hasRuntime = true  
```

### Key **Characteristics of var**

1.  **Function Scope**: Variables declared with `var` are scoped to the nearest function block, not to block-level constructs like `if`, `for`, or `try-catch`.
    
2.  **Hoisting**: `var` declarations are hoisted to the top of their scope (function or global), meaning they are moved to the top during compilation. However, only the declaration is hoisted — initialization happens at the original line.
    
3.  **Redeclaration**: You can redeclare the same `var` variable multiple times in the same scope without an error.
    
4.  **Global Object Property**: In a script, a `var` variable becomes a non-configurable property of the global object (`window` in browsers), making it difficult to delete.
    
5.  **No Block Scope**: Unlike `let` and `const`, `var` does not respect block scope (e.g., `{}`), so variables can be accessed outside the block they were declared in.
    

* * *

### Let

`let` is a modern keyword introduced in **ES6 (ECMAScript 2015)** for declaring variables in JavaScript. It provides **block scope**, meaning variables declared with `let` are only accessible within the block, statement, or expression where they are defined—unlike `var`, which has function scope.

```javascript
let programmingLanguage = "Java"
let developIn = 1996

let supportCrossPlateform = true
```

### Key Characteristics of let

1.  **Block Scoping**: Variables are confined to the nearest block (e.g., `{}` in `if`, `for`, `while` statements).
    
2.  **No Redeclaration**: You cannot declare the same variable twice in the same scope.
    
3.  **Temporal Dead Zone (TDZ)**: `let` variables are hoisted but not initialized. Accessing them before declaration throws a `ReferenceError`.
    
4.  **Reassignable**: Values can be changed after declaration, but the variable name cannot be reused.
    

* * *

### Const

**const** variables in JavaScript are **hoisted** to the top of their block scope, similar to `let`, but they are **not initialized** during hoisting. This creates a **Temporal Dead Zone (TDZ)** — a period from the start of the block until the variable's declaration is executed — during which accessing the variable throws a `ReferenceError: Cannot access 'variable' before initialization`.

```javascript
const programmingLanguage = "Java"
const developIn = 1996

const supportCrossPlateform = true
```

### Key Characteristic of const

1.  **Hoisting**: Yes, `const` declarations are hoisted to the top of their scope.
    
2.  **Initialization**: No, `const` variables are not initialized during hoisting.
    
3.  **Temporal Dead Zone (TDZ)**: The variable is inaccessible until its declaration is executed.
    
4.  **Error on Access Before Declaration**: `ReferenceError: Cannot access 'x' before initialization` is thrown.
    
5.  **Must Be Initialized**: `const` variables must be assigned a value at the time of declaration.
    

* * *

### let vs const vs var

JavaScript provides three ways to declare variables: var, let, and const, but they differ in scope, hoisting behaviour, and re-assignment rules.

*   **var:** Declares variables with function or global scope and allows re-declaration and updates within the same scope.
    
*   **let:** Declares variables with block scope, allowing updates but not re-declaration within the same block.
    
*   **const:** Declares block-scoped variables that cannot be reassigned after their initial assignment.
    

* * *

### Data Types In javascript

1.  ### String
    

string is a primitive data types which is used to represent textual data such as name, message etc.. . string is an immutable we can't modify the existing data. Any operation which modify the existing data result in returning a new string.

### **Creating Strings**

Strings can be created using:

*   **Single quotes**: `'Hello'`
    
*   **Double quotes**: `"World"`
    
*   **Template literals (backticks)**: `Hello ${name}`
    

Template literals are especially powerful as they support **string interpolation** (embedding variables and expressions with `${}`), **multi-line strings**, and **tagged templates**.

### Common Methods of String

*   `lenght()`: lenght function used to return the lenght of the string
    
*   `charAt(index)` : charAt function is used to get the character at the given index.
    
*   `includes(subStr)` : return `true` if string contain the substring.
    
*   `slice(start, end)` : Extract portion of the string.
    
*   `indexOf(substr)` : Returns the first occurrence of a substring, or `-1` if not found.
    
*   `replace(old, new)` : Replaces the first occurrence of a substring.
    
*   `toUpperCase()` / `toLowerCase()` : Converts the string to uppercase or lowercase.
    

```javascript
let str = "javascript"

// Method 
// 1. length 
let result = str.length
console.log(result);

// 2. charAt()
result = str.charAt(7)
console.log(result)

// 3. includes()
result = str.includes('scr')
console.log(result)

// 4. IndexOf() & valueOf
// NOTE:- return the index of the char in the string
result = str.indexOf('s')
console.log(result)

// NOTE:- Return the value 
result = str.valueOf()
console.log(result)

result = str.slice(5)
console.log(result)

result = str.split("")
console.log(result)
```

### String Conversion

1.  `String()` **Constructor**  
    The most straightforward and reliable method. It works for all data types, including `null`, `undefined`, and `NaN`.
    

```javascript
String(123);        // "123"
String(null);       // "null"
String(undefined);  // "undefined"
String(true);       // "true"
```

2.  `.toString()` **Method**  
    Available on most data types (numbers, booleans, arrays), but **throws an error if used on** `null` **or** `undefined`.
    

```javascript
(123).toString();     // "123"
true.toString();      // "true"
[1, 2].toString();    // "1,2"
// null.toString();  // TypeError!
```

3.  **Template Literals (Backticks)**  
    A clean, readable way, especially useful when embedding values in text.
    

```javascript
`Value: ${123}`;     // "Value: 123"
`Status: ${true}`;   // "Status: true"
```

4.  **Concatenation with Empty String**  
    Uses JavaScript’s type coercion by adding an empty string (`""`) to the value.
    

```javascript
123 + "";     // "123"
true + "";    // "true"
```

5.  `JSON.stringify()`  
    Ideal for converting objects, arrays, and complex data structures to strings. It serializes data into JSON format.
    

```javascript
JSON.stringify({name: "John"});  // "{"name":"John"}"
JSON.stringify([1, 2]);         // "[1,2]"
JSON.stringify(null);            // "null"
```

6.  `new String()` **(Not Recommended)**  
    Creates a **String object** rather than a primitive string. Avoid unless you specifically need object behavior (e.g., storing properties).
    

```javascript
typeof new String("hello");  // "object"
```

7.  `Object.prototype.toString.call()`  
    Advanced method used for debugging or detecting types. Can be adapted to convert values, but not ideal for simple string conversion.
    

```javascript
Object.prototype.toString.call(123);  // "[object Number]"
```

8.  `Array.prototype.join()`  
    Converts a value to a string by placing it in an array and joining it. Useful for arrays or when working with number sequences.
    

```javascript
[123].join("");  // "123"
```

9.  `+` **and** `.toString()` **(Creative Use)**  
    Use `+` to coerce to number, then `.toString()` to convert back—rarely used but demonstrates type coercion.
    

```javascript
(+ "123").toString();  // "123"
```

10.  `parseInt()` **and** `.toString()`  
     Ensures input is a valid number before conversion—useful when dealing with number strings.
     

```javascript
parseInt("123", 10).toString();  // "123"
```

* * *

### Number

Number is a primitive data type which is used to represent the Integer, floating value and BigInteger in the world of the programming language. They follow the **64-bit double-precision IEEE 754 standard**, meaning all numbers in JavaScript are stored as floating-point values, even whole numbers like `5` or `100`.

### **Key Features of JavaScript Numbers**

*   **Floating-Point Representation**: There is no separate integer type; `37` is stored as a floating-point number.
    
*   **Range and Precision**:
    
    *   Maximum safe integer: `Number.MAX_SAFE_INTEGER` = `9007199254740991` (2⁵³ − 1).
        
    *   Minimum safe integer: `Number.MIN_SAFE_INTEGER` = `-9007199254740991`.
        
    *   Largest representable number: `Number.MAX_VALUE` ≈ `1.7976931348623157e+308`.
        
    *   Smallest positive number: `Number.MIN_VALUE` ≈ `5e-324`.
        
*   **Special Values**:
    
    *   `Infinity`: Result of dividing a positive number by zero (`2 / 0`).
        
    *   `-Infinity`: Result of dividing a negative number by zero (`-2 / 0`).
        
    *   `NaN` (Not a Number): Returned when a mathematical operation fails (e.g., `4 - "hello"`).
        

### **Number Literals**

JavaScript supports multiple number formats:

*   **Decimal**: `123`, `-456`
    
*   **Binary**: `0b1010` or `0B1010`
    
*   **Octal**: `0o755` (standard) or `0755` (legacy, not allowed in strict mode)
    
*   **Hexadecimal**: `0xFF`, `0x1A3`
    
*   **Exponential**: `1.23e5` (equivalent to `123000`)
    

### **Number Conversion**

*   `Number(value)`: Converts a value to a number. Returns `NaN` if conversion fails.
    
    ```javascript
    Number("123")     // 123
    Number("abc")     // NaN
    Number(true)      // 1
    Number(null)      // 0
    ```
    
*   `parseInt()`: Parses a string and returns an integer.
    
*   `parseFloat()`: Parses a string and returns a floating-point number.
    

### **Number Methods and Properties**

*   `Number.isFinite()`: Checks if a value is a finite number.
    
*   `Number.isInteger()`: Checks if a value is an integer.
    
*   `Number.isNaN()`: Checks if a value is `NaN`.
    
*   `Number.isSafeInteger()`: Checks if a value is a safe integer.
    
*   `Number.EPSILON`: Smallest difference between two representable numbers (~2⁻⁵²).
    
*   `Number.MAX_VALUE`**,** `MIN_VALUE`**,** `MAX_SAFE_INTEGER`**,** `MIN_SAFE_INTEGER`: Constants for numeric limits.
    

### **BigInt for Large Integers**

For integers outside the safe range, use **BigInt** (suffix `n`):

```javascript
const bigNum = 123456789012345678901234567890n;
```

*   **BigInt** supports arbitrary precision but **cannot represent decimals** and **does not work with** `Math` **functions**.
    

* * *

### Boolean

**JavaScript Booleans** are a fundamental data type that can only have two values: **true** or **false**. They are used to represent logical states and control program flow in conditional statements (like `if`, `while`) and loops.

### **Boolean Primitive vs. Boolean Object**

*   **Boolean primitive** (`true`, `false`): The standard, recommended way to use booleans. It is a simple value with `typeof` returning `"boolean"`.
    
*   **Boolean object** (`new Boolean()`): A wrapper object created with the `new` keyword. While it can store a boolean value, it is **discouraged** because:
    
    *   `typeof` returns `"object"`, not `"boolean"`.
        
    *   All objects are truthy, so even `new Boolean(false)` evaluates to `true` in a conditional.
        
    *   It can cause confusion and unexpected behavior.
        

### **Converting Values to Boolean**

JavaScript uses **truthy** and **falsy** values to determine boolean conversion:

*   **Falsy values** (coerce to `false`): `0`, `-0`, `0n`, `null`, `undefined`, `NaN`, `""` (empty string).
    
*   **Truthy values** (coerce to `true`): All other values, including non-empty strings, arrays, objects, and `false` as a string.
    

Use the `Boolean()` **function** (without `new`) or the **double NOT operator (**`!!`**)** to convert any value to a boolean primitive:

```javascript
Boolean("hello");     // true
!!"";                  // false
```

* * *

### Null

**null** in JavaScript is a **primitive value** representing the **intentional absence of any object value**. It is explicitly assigned by developers to indicate that a variable or property has no meaningful value at the moment, but may be assigned one later.

### **Key Characteristics of** `null`**:**

*   **Purpose**: Signifies an **intentional empty value** (e.g., clearing a variable, indicating no object reference).
    
*   **Type**: Despite being a primitive, `typeof null` returns `"object"` — a long-standing bug in JavaScript that has been preserved for backward compatibility.
    
*   **Equality**:
    
    *   `null == undefined` → `true` (loose equality, due to type coercion).
        
    *   `null === undefined` → `false` (strict equality, different types).
        
*   **Numeric Context**: `null` is coerced to `0` in arithmetic operations (e.g., `2 + null` → `2`).
    
*   **JSON Handling**: `JSON.stringify()` can represent `null` faithfully, unlike `undefined`.
    
*   **Usage Examples**:
    
    ```javascript
    let user = null; // Intentionally empty
    const element = document.getElementById('nonexistent'); // Returns null if not found
    ```
    

### **When to Use** `null`**:**

*   When you **explicitly want to indicate no value** (e.g., resetting a variable, API responses with no data).
    
*   When designing APIs, `null` is often preferred over `undefined` to signal deliberate absence.
    

* * *

### Undefined

**undefined** in JavaScript is a primitive value automatically assigned to variables that have been declared but not initialized, or to properties and function return values that do not exist or are not explicitly returned.

*   **When it occurs**:
    
    *   A variable declared without a value: `let x; console.log(x); // undefined`
        
    *   Accessing a non-existent object property: `let obj = {}; console.log(obj.nonExistent); // undefined`
        
    *   A function that doesn’t return a value: `function noReturn() {} console.log(noReturn()); // undefined`
        
    *   An unused function parameter: `function test(param) { console.log(param); } test(); // undefined`
        
*   **Key characteristics**:
    
    *   `typeof undefined` returns `"undefined"` (the only primitive with this type).
        
    *   `undefined` is a **global property** and should not be reassigned.
        
    *   `undefined` is **not** the same as `null` — `null` is an intentional absence of value, while `undefined` means no value has been assigned.
        
*   **How to check for it**:
    
    *   Use strict equality: `variable === undefined`
        
    *   Use `typeof`: `typeof variable === 'undefined'`
        
    *   Avoid `==` (loose equality) as it treats `undefined` and `null` as equal (`undefined == null` is `true`).
        

* * *

### Symbols

**Symbol** is a primitive data type in JavaScript introduced in ES6 (ECMAScript 2015). It represents a unique and immutable value, guaranteed to be distinct from all other symbols, even if they share the same description.

### **Key Features of Symbols**

*   **Uniqueness**: Each `Symbol()` call returns a new, unique symbol. Even symbols with identical descriptions are not equal:
    
    ```javascript
    const sym1 = Symbol('id');
    const sym2 = Symbol('id');
    console.log(sym1 === sym2); // false
    ```
    
*   **Non-enumerable**: Symbols used as object keys are not included in `for...in` loops, `Object.keys()`, or `JSON.stringify()`, making them ideal for hidden or internal properties.
    
*   **No Automatic String Conversion**: Symbols cannot be implicitly converted to strings, preventing accidental misuse:
    
    ```javascript
    const id = Symbol('id');
    // alert(id); // TypeError: Cannot convert a Symbol value to a string
    ```
    

### **Creating and Using Symbols**

*   **Scoped Symbols**: Created with `Symbol()`:
    
    ```javascript
    const mySymbol = Symbol('description');
    ```
    
*   **Global Symbols**: Registered in a global registry using `Symbol.for(key)`:
    
    ```javascript
    const globalSym = Symbol.for('sharedKey');
    const sameSym = Symbol.for('sharedKey');
    console.log(globalSym === sameSym); // true
    ```
    
    Use `Symbol.keyFor(sym)` to retrieve the key from a global symbol.
    

### **Common Use Cases**

*   **Avoiding Property Collisions**: Safely add unique keys to objects without risk of overwriting existing properties.
    
*   **Private/Hidden Properties**: Attach metadata or internal state to objects that won’t be exposed during serialization or iteration.
    
*   **Customizing Object Behavior**: Well-known symbols (e.g., `Symbol.iterator`, `Symbol.toPrimitive`) allow developers to define custom behavior for built-in operations like iteration or type conversion.
    

### **Important Notes**

*   Symbols are **not** constructors and **cannot** be used with `new`.
    
*   They are **not** garbage collectable if registered globally, but **are** garbage collectable if scoped.
    
*   Well-known symbols (like `Symbol.hasInstance`) are predefined and used internally by JavaScript to customize language behavior.
    

* * *

### Object

An **object in JavaScript** is a collection of key-value pairs, where each key (also called a property name) is a string or symbol, and each value can be any data type—such as a primitive (string, number, boolean), another object, or a function. Objects are fundamental to JavaScript and are used to represent real-world entities, like a car, person, or course. Object is a non primitive data type.

### **Syntax and Creation**

Objects are typically created using **object literal syntax** with curly braces `{}`:

```javascript
const person = {
  name: "Alice",
  age: 25,
  greet: function() {
    return "Hello!";
  }
};
```

*   **Properties** are defined as `key: value` pairs.
    
*   If a property’s value is a function, it’s called a **method**.
    
*   Multiword keys must be quoted: `"full name": "Alice Smith"`.
    
*   **Computed properties** use square brackets: `[key] = value`.
    

### **Accessing Properties**

Use **dot notation** (`obj.property`) or **bracket notation** (`obj["property"]`) to access values:

```javascript
console.log(person.name); // "Alice"
console.log(person["age"]); // 25
```

Bracket notation allows dynamic property access using variables or expressions.

### **Key Features**

*   **Dynamic**: Properties can be added, modified, or deleted at runtime:
    
    ```javascript
    person.job = "Developer";
    delete person.age;
    ```
    
*   **Reference Type**: Objects are passed by reference, not by value.
    
*   **Prototypal Inheritance**: Every object has an internal link to a prototype object (via `[[Prototype]]`), enabling inheritance.
    

### **Common Methods**

JavaScript provides built-in methods to manipulate objects:

*   `Object.keys(obj)` – returns an array of property names.
    
*   `Object.values(obj)` – returns an array of values.
    
*   `Object.assign(target, source)` – copies properties from one or more sources to a target.
    
*   `Object.create(proto)` – creates a new object with a specified prototype.
    

Objects are central to JavaScript’s object-oriented programming model and are used extensively in real-world applications.

* * *

### Arrays

**Arrays in JavaScript** are ordered collections of values that can store multiple items under a single variable name. They are zero-indexed, meaning the first element is at index `0`, and they can hold any data type—numbers, strings, objects, or even other arrays—making them highly flexible. In javascript, Arrays are also an object in javascript.

### **Creating Arrays**

*   **Array literals** (most common): Use square brackets `[]` to define and initialize an array.
    
    ```javascript
    const fruits = ["apple", "banana", "cherry"];
    ```
    
*   **Array constructor**: Use `new Array()` (less common due to potential inconsistencies).
    
    ```javascript
    const numbers = new Array(1, 2, 3);
    ```
    

### **Key Features**

*   **Dynamic size**: Arrays automatically grow or shrink as needed.
    
*   **Mixed data types**: A single array can contain different types of values.
    
*   **Length property**: Access the number of elements using `.length`.
    
    ```javascript
    console.log(fruits.length); // 3
    ```
    

### **Common Array Methods**

*   **Accessing elements**: Use bracket notation with index.
    
    ```javascript
    console.log(fruits[0]); // "apple"
    ```
    
*   **Adding elements**:
    
    *   `push()` adds to the end.
        
    *   `unshift()` adds to the beginning.
        
*   **Removing elements**:
    
    *   `pop()` removes from the end.
        
    *   `shift()` removes from the beginning.
        
    *   `splice()` removes or replaces elements at a specific index.
        
*   **Searching and checking**:
    
    *   `indexOf()` returns the index of the first match or `-1` if not found.
        
    *   `includes()` returns `true` if the value exists.
        
    *   `find()` and `findIndex()` return the first element or its index that passes a test.
        
*   **Iterating**:
    
    *   `forEach()` executes a function for each element.
        
    *   `map()` creates a new array with transformed values.
        
    *   `filter()` returns a new array with elements that pass a test.
        
*   **Modifying**:
    
    *   `sort()` sorts elements (alphabetically for strings, numerically for numbers).
        
    *   `reverse()` reverses the order of elements.
        
    *   `slice()` extracts a portion of the array without modifying the original.
        
    *   `concat()` joins arrays into a new array.
        

### **Important Notes**

*   **Shallow copying**: Methods like `slice()` and `concat()` create shallow copies. Nested objects are referenced, not duplicated.
    
*   **Sparse arrays**: Setting a high index without filling intermediate slots creates empty slots (not `undefined`), which can affect iteration behavior.
    
*   **Non-integer keys**: Arrays should use nonnegative integers as indices. Using string keys (e.g., `arr["key"]`) creates object properties, not array elements.
    

Arrays are fundamental to JavaScript and essential for managing collections of data efficiently, especially in loops, data processing, and complex applications.

* * *

### Function

**Functions in JavaScript** are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code by taking inputs (parameters), performing actions, and optionally returning outputs. In javascript, function is also another data type in javascript

```javascript
function example() {
    return "hello world"
} 

console.log(typeof example)
```

### **Function Declaration**

The most common way to define a function is using a **function declaration**:

```javascript
function greet(name) {
  return "Hello, " + name + "!";
}
```

*   Starts with the `function` keyword.
    
*   Includes a function name (e.g., `greet`), parameters in parentheses `(name)`, and a code block in curly braces `{}`.
    
*   Can be **hoisted**, meaning it can be called before it's defined in the code.
    

### **Function Expression**

Functions can also be defined as expressions, often assigned to variables:

```javascript
const square = function (number) {
  return number * number;
};
```

*   Functions defined this way are not hoisted (unless using `let`/`const`).
    
*   Can be **anonymous** or **named** (e.g., `fac` in `const factorial = function fac(n) { ... }`).
    

### **Arrow Functions (ES6+)**

A concise syntax for writing functions, especially useful for callbacks:

```javascript
const add = (a, b) => a + b;
```

*   Uses the `=>` syntax.
    
*   Does **not have its own** `this` **binding**, making it ideal for functional programming.
    

### **Key Concepts**

*   **Parameters vs. Arguments**: Parameters are placeholders in the function definition; arguments are the actual values passed during a call.
    
*   **Return Statement**: Ends function execution and returns a value. If omitted, the function returns `undefined`.
    
*   **Default Parameters**: Allow setting fallback values if no argument is provided:
    
    ```javascript
    function greet(name = "Guest") {
      return "Hello, " + name;
    }
    ```
    
*   **Rest Parameters**: Capture a variable number of arguments into an array:
    
    ```javascript
    function sum(...numbers) {
      return numbers.reduce((a, b) => a + b, 0);
    }
    ```
    

Functions are fundamental to JavaScript, enabling modularity, reusability, and clean code structure. They can be passed as arguments, returned from other functions, and used in callbacks, closures, and higher-order functions like `map`, `filter`, and `reduce`.

* * *

### Final Words in javascript

JavaScript has **8 primary data types**, categorized into **primitive** and **non-primitive (reference)** types.

### **Primitive Data Types**

These are immutable, directly stored in memory, and represent single values:

*   `string`: Textual data, enclosed in quotes (e.g., `"hello"`).
    
*   `number`: Numeric values, including integers and floating-point numbers (e.g., `42`, `3.14`).
    
*   `bigint`: Large integers with arbitrary precision (e.g., `9007199254740991n`).
    
*   `boolean`: Logical values, either `true` or `false`.
    
*   `undefined`: A variable declared but not assigned a value.
    
*   `null`: Represents intentional absence of any object value.
    
*   `symbol`: Unique and immutable identifiers, often used for object properties.
    

### **Non-Primitive (Reference) Data Type**

*   `object`: A collection of key-value pairs (e.g., `{ name: "John" }`). Includes arrays, functions, dates, maps, sets, and more.
    

### **Examples**

```javascript
let name = "Alice";           // string
let age = 25;                 // number
let isStudent = true;         // boolean
let bigNum = 123456789012345678901234567890n; // bigint
let id = Symbol("id");        // symbol
let value = null;             // null
let status;                   // undefined
let user = { name: "Bob" };   // object
```
