Avatar of Charlie_S24
 asked on

Why is my local Javascript array's being modified in external functions?

Although I thought I understood how local and public variables work with JavaScript, I still have a function modifying my two-dimensional array.  I'm not sure how to prevent that from happening.  (Have I declared the array properly?  Am I passing it properly?)

My goal is to have a two-dimensional array in the main routine whose data is passed to a function that uses the data, but leaves the original array in the main routine untouched.

Below is a little bit of fictitious code that duplicates the problem.  

Your help would be appreciated.

<p id="demo">Click the button to test code.</p>
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">

function myFunction()
  var aryFirstArray =  new Array(1)
  aryFirstArray[0] = new Array()
  aryFirstArray[0][0] = "I am expecting the 2nd dimension to still be 5: "
  aryFirstArray[0][1] = 5
  var x=document.getElementById("demo");
function myOtherFunction(aryDifferentArray)
  aryDifferentArray[0][1] = 4
Scripting Languages

Avatar of undefined
Last Comment
Michel Plungjan

8/22/2022 - Mon
Michel Plungjan

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Your help has saved me hundreds of hours of internet surfing.