Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Passing objects to functions can be tricky, JavaScript passes objects sort of by reference that means when you change the object in the function it'll be changed after the function is done:</p> <pre><code>function sortmyarray(arr){ arr.sort(); } function test(){ var arr=[3,2,1]; sortmyarray(arr); console.log(arr);//[1,2,3] } test(); </code></pre> <p>This only works when you invoke a function that changes the object, assigning a new value would not work:</p> <pre><code>function sortmyarray(arr){ arr=[1,2,3]; } function test(){ var arr=[3,2,1]; sortmyarray(arr); console.log(arr);//[3,2,1] } test(); </code></pre> <p>But you can re assign a value to arr in test by a value returned from sortmyarray</p> <pre><code>function sortmyarray(arr){ return "hello world"; } function test(){ var arr=[3,2,1]; arr=sortmyarray(arr); console.log(arr);//"hello world" } test(); </code></pre> <p>As to why passing objects to a function; it is so you can re use code here is a sort function that is re used:</p> <pre><code>var myObj={ toString:function(){ var ret=[];i=0; for(i=0;i&lt;this.arr.length;i++){ ret.push(this.arr[i].col1); ret.push("\t"); ret.push(this.arr[i].col2); ret.push("\n"); } return ret.join(""); }, arr:[ {col1:99,col2:1}, {col1:1,col2:3}, {col1:3,col2:1}, {col1:1,col2:99} ] } function sortmyarray(arr, byColNames){ var len=byColNames.length; arr.sort(function(a,b){ var i=0; while(a[byColNames[i]]===b[byColNames[i]] &amp;&amp; i&lt;len){ i++; } if(i===len){ return 0; } return(a[byColNames[i]]&gt;b[byColNames[i]])?1:-1; }); } sortmyarray(myObj.arr,["col2"]) console.log(myObj.toString()); sortmyarray(myObj.arr,["col2","col1"]); console.log(myObj.toString()); sortmyarray(myObj.arr,["col1","col2"]); console.log(myObj.toString()); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload