Search code examples
javascriptarraysconstantsimmutabilitymutability

Declaring an array with const keyword Javascript


I have created an array - const cars = ["Saab", "Volvo", "BMW"]; Now if I try to reassign values at specific indexes, it works like - cars[0] = "Toyota"; cars[1] = "Honda"; cars[2] = "Hyundai"; but when I try to reassign it at single time like cars = ["Toyota" , "Honda" , "Hyundai"] , it throws an error. I am not able to understand the mutability vs reassigning concept here.


Solution

  • const str = 'abcd';
    str = 'changed'; //error
    
    
    const list = [1,2,3]; // Assume this array is created on memory loc 0x001 (imaginary)
    
    list[0] = 200; // no error  here the memory location remains constant but the content changes.
    
    list = [6,4,2]; // error Here new assignment hence memory location changes so error
    

    Arrays or objects are mapped by location and not value compared to strings/numbers.