Datatype , Memory( Stack & Heap ) in JS:

Datatype , Memory( Stack & Heap ) in JS:

Datatype: Basically, we do our operation/task in any programming language on different types of data. So for an operation, we have to create a variable means container in memory and for recognition of this container comes the concept of datatype. So datatype help us to store separate data in different type of variable.

In Javascript, there are two types of data types based on their sizes, memory allocation etc.: Primitive and non-primitive/Reference

Primitive Datatype: It is immutable, which means its values cannot be changed after being assigned. JavaScript has 7 primitive data types: String, Number, Boolean, BigInt, null, undefined, symbol

Non-Primitive: These are not directly stored in variables but instead are stored as references to objects in memory.JavaScript has three main non-primitive data types:

  1. Object: Objects are collections of key-value pairs and are used to represent complex data structures. They can contain a combination of primitive and non-primitive data types. Objects can have properties and methods. For example:

     let person = {
         firstName: "Aditya",
         lastName: "Evans",
         age: 21,
         sayHello: function() {
             console.log("Hello, " + this.firstName + " " + this.lastName);
         }
     };
    
  2. Array: Arrays are collections of values and are used to store lists of items. Arrays have built-in methods for manipulating and accessing their elements. For example:

     let colors = ["red", "green", "blue"];
     let numbers = [1, 2, 3, 4, 5];
    
  3. Function: Functions are objects in JavaScript and are used to define reusable blocks of code that can be executed when called. Functions can also have properties and methods. For example:

     function greet(name) {
         console.log("Hello, " + name + "!");
     }
    

Non-primitive data types are passed by reference. When you assign a non-primitive value to a variable or pass it as an argument to a function, you're working with a reference to the underlying object in memory. Any changes made to the object are reflected in all references to it. This is different from primitive data types, which are passed by value and result in independent copies.

Memory: There are mainly two types of memory used in JS: Stack and heap.

Stack memory is used for primitive data type and it provide a copy of memory during another value assigned in a variable. but heap is used for non-primitive data types and it provides the original memory, not a copy.