Search code examples
javascriptstringconstantsmutablelet

string in javascript are immutable, but when we use let with strings , it becomes changeable,


string in JavaScript are immutable, but when we use 'let' with strings , it becomes changeable, which tends to mean that they are mutable, how can we justify that strings are immutable yet it is mutable when use with let?


Solution

  • Let me help you with that using an example.

    Consider we declare a string using let

    let someString = 'This is a String'
    

    now you can Re-assign that variable someString to a new value which means let variables can be reassigned.

    someString = 'Some new Value'
    

    But Strings are immutable in the sense that you can't mutate the content of the String.

    someString[1] = 'A' //This is Invalid since Strings are Immuatable
    

    Happy Coding :)