I've created the following javascript code:
let myVector = ['one', 'two', 'three', 'four', 'five']
testFunction(myVector)
console.log(myVector)
function testFunction(vector) {
for (var i = 0, len = vector.length; i < len; i++) {
vector[i] = vector[i] + ": " + i
}
return vector
}
When I execute this code printing the value of myVector
I get the following result:
[ 'one: 0', 'two: 1', 'three: 2', 'four: 3', 'five: 4' ]
I don't get how it's possible. I'm probably missing some very fundamental concept of javascript... In my mind, this should only happen if my code were as the following:
let myVector = ['one', 'two', 'three', 'four', 'five']
console.log(testFunction(myVector))
function testFunction(vector) {
for (var i = 0, len = vector.length; i < len; i++) {
vector[i] = vector[i] + ": " + i
}
return vector
}
On my first sample, I never reasigned a value to myVector
... I expected it to print ['one', 'two', 'three', 'four', 'five']
instead of [ 'one: 0', 'two: 1', 'three: 2', 'four: 3', 'five: 4' ]
. Why Javascript is changing the value of a parameter that was sent to it? Shouldn't its modifications be valid only inside the function? What would be an alternative way of creating this code in a way that I avoid it to happen?