skip to Main Content

Can somebody explain this behaviour

Code:

name = "ABC"
console.log(name)

name[0] = "B"
console.log(name)

Output Expected:

ABC
BBC

Actual Output :
Actual Output

2

Answers


  1. Strings are immutable/readonly due to the fact that they are primitive data types in JavaScript. You can only generate new strings.

    name = "ABC"
    console.log(name)
    
    name = "B" + name.slice(1);
    console.log(name)
    

    To read more about primitives-MDN-Primitives

    Login or Signup to reply.
  2. By creating a new string with the desired modification, you achieve the desired result while keeping the original name variable intact.

    let name = "ABC";
    console.log(name);
    
    name = "B" + name.substring(1); // Concatenate "B" with the rest of the string
    console.log(name);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search