[solved] Strings are immutable. Array vars are mutable. But what about String data in an Array?

If I have an array…

var myArray = ["Banana', 4];

…and I try to modify the first element in myArray by…

myArray[0] = "Apple";

…what will happen?
I haven’t figured out how to test stuff with a code editor (all I use is brackets for webDev).

…and then i read @camperextraordinaire’s reply on how to test it lol.

The best way to answer this question is to try it for yourself :smile:

If you have Brackets and a browser, all you need to do is put your javascript code between script tags in an html page and open it in your browser. You can ‘print’ things from your code to the ‘console’ which you’ll find if you open the developer tools of your browser.

Here’s an example


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

    <script type="text/javascript">
      let myArray = ["Banana", 4];
      console.log(`my array is: ${myArray}`);
      myArray[0] = "Apple";
      console.log(`and now it's... ${myArray}`);
    </script>
  </body>
</html>

Using the devTool and the example above

console.log(myArray);

produces

(2) ["Apple", 4]

This means that Strings in Arrays are mutable, RandelDawson gets the Hero of the day award, and I am officially Super Cool because I know how to use a Chrome devTool.

But seriously, Strings in Arrays are mutable.

I posted one second to late for ya @r1chard5mith lol
The Chrome devTool works great for me. It’s just so convenient.
But thanks for showing me that JavaScript thing I could use in Brackets because that’s handy in itself.

I didn’t realise I could make new threads with questions, answer my own questions and accept my own answer as the solution. Thanks for showing me that neat trick. :stuck_out_tongue_winking_eye:

1 Like

Well…I asked the question, answered it for myself before someone else could, then solved it so others could use it when they search.
I can teach you the ways of the force @r1chard5mith :laughing: :laughing:

I think strings are immutable, regardless of whether they are items in an array or not. What you have done is replace an item in the array, which was a string, with a new item, which just happens to be a different string, You haven’t altered the original string, you’ve only altered array items both of which happened to be strings.

4 Likes

:thinking::thinking::thinking::grinning::grinning:
Yes. :musical_score:I can see clearly now three rain is gone…