Articles → JAVASCRIPT → Value Type And Reference Type In Javascript

Value Type And Reference Type In Javascript






Purpose


  1. In case of the value type, a memory location is allocated and the actual value is stored in it. Number, boolean, null are examples of value types.
  2. In case of reference type, a memory location is allocated and the reference of another memory location is stored in it. Arrays and objects are examples of the value type.
Picture showing the pictorical representation of value type and reference type in Javascript



How Is The Copy Done In Value Type?




<script>
var number = 1;
var number2 = number;
console.log("number:" + number);
console.log("number2:" + number2);

number = 2;
console.log("number:" + number);
console.log("number2:" + number2);
</script>






Picture showing how the copy is done in case of value type



How Is The Copy Done In Reference Type?




<script>
        
        var person = {
            name : "gyan"
        };       

        var anotherPerson = person;
        // This code copies the pointer from one object to another
        person.name = "gyansangrah";

        console.log(person.name);
        console.log(anotherPerson.name);

</script>






Picture showing how the copy is done in case of reference type



Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, August 25, 2021

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250