I have two function that accept an array as parameter, these function do a simple work, making all element of the array to zero.
First function using forEach()
method and passing a callback to it:
function pass_arr(x)
{
x.forEach(function(y){
y = 0;
});
}
And I call it this way:
var a = ["a", "b", 1, 3, "stringg"];
pass_arr(a);
Then printing the content of array a:
for(var i = 0; i < a.length; i++)
{
console.log(a[i]);
}
I execute this using node:
#nodejs func.js
and got the result
a
b
1
3
stringg
Second function using normal function call :
function pass_arr(x)
{
for(var i = 0; i < a.length; i++)
{
x[i] = 0;
}
}
var a = ["a", "b", 1, 3, "stringg"];
pass_arr(a);
for(var i = 0; i < a.length; i++)
{
console.log(a[i]);
}
#node func.js
And got the result :
0
0
0
0
0
As far as i know when we pass an array to a function, then we do
pass by referenceand thus we can modify the content of the array inside the function.
My question is why the first function doesn't properly zeroing the content of the array? Please give some clear explanation?