What will the code below output to the console and why?
var arr1 = "john".split('');
var arr2 = arr1.reverse();
var arr3 = "jones".split('');
arr2.push(arr3);
console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(-1));
console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(-1));
Out Put will be : "array 1: length=5 last=j,o,n,e,s" "array 2: length=5 last=j,o,n,e,s"
Here's an answer that was posted with this question. However, i don't understand what javascript principle or rules that this is following?
"The reverse() method returns a reference to the array itself (i.e., in this case, arr1). As a result, arr2 is simply a reference to (rather than a copy of) arr1. Therefore, when anything is done to arr2 (i.e., when we invoke arr2.push(arr3);), arr1 will be affected as well since arr1 and arr2 are simply references to the same object."
reverseis in-place algorithm.var x = [1,2,3]; x.reverse(); console.log(x); // => [3,2,1]Note how you didn't have to assignx.reverse()to another variable; instead, the operation was performed on the array. Conversely, operations like.mapwon't work like that:x.map(function (d) { return d * 2; }); console.log(x); // => [3,2,1], since they don't work off a referencevar a = b.reverse()is that b is reversed and a is assigned a reference to it, so both a and b reference the same array.