By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,851 Members | 1,051 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,851 IT Pros & Developers. It's quick & easy.

Modifying a variable in a forEach loop

P: n/a
Hi

I would have expected the following to change the value of a, but just
discovered it doesn't.

var forEach = function () {
var a = "a";
[a].forEach(function (v, i) {
console.log("v=" + v);
v = i;
console.log("v=" + v);
});
console.log("a=" + a);
};

The output is:
v=a
v=0
a=a

I'm not really sure why, I'd be very grateful if someone could
explain.
Thanks

Paul
Oct 7 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On Oct 7, 7:15 pm, Paul Carey <paul.p.ca...@gmail.comwrote:
Hi

I would have expected the following to change the value of a, but just
discovered it doesn't.

var forEach = function () {
var a = "a";
[a].forEach(function (v, i) {
console.log("v=" + v);
v = i;
console.log("v=" + v);
});
console.log("a=" + a);

};

The output is:
v=a
v=0
a=a

I'm not really sure why, I'd be very grateful if someone could
explain.
In javascript, plain numbers and strings are passed by value. Only
objects are passed by reference. If we modify your code slightly
you'll see the expected behavior:

var forEach = function () {
var a = {value:"a"};
[a].forEach(function (v, i) {
console.log("v",v);
v.value = i;
console.log("v",v);
});
console.log("a",a);
};

output:
v Object value=a
v Object value=0
a Object value=0

Oct 8 '08 #2

P: n/a
slebetman wrote:
On Oct 7, 7:15 pm, Paul Carey <paul.p.ca...@gmail.comwrote:
>
In javascript, plain numbers and strings are passed by value. Only
objects are passed by reference. If we modify your code slightly
you'll see the expected behavior:
Actually, object references are passed by value.

Garrett
Oct 8 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.