Javascript sorting function question

Javascript sorting function question
0

#1

Hi, I have a general javscript question.

var gimme = function (inputArray) {
	var givenArr = inputArray;
	var newArr = inputArray.sort(function(a,b){
		return a-b;
	});
	
	console.log(givenArr);
	console.log(inputArray);
	
	
};

gimme([2, 3, 1]);

output for both inputArray and givenArr is same, why is that? I thought inputArray will be updated only after the sorting function is called.

Please respond.


#2

When you wrote:

var givenArr = inputArray;

you are passing a reference of the inputArray to the variable givenArr.

An array in JavaScript is a specialized object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object. Any changes you make to givenArr, will affect inputArray, because they both reference the same underlying object.