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

Click to Enlarge


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

Click to Enlarge


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

Click to Enlarge


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

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250