When I started my formal education in computer science, I had to take a module on programming with the C language. I remember this was a module that caused many of my peers to re-think their decision to study computer engineering; the concept of pointers was so foreign to many of them that even the smart ones scored poorly.
Memory-managed programming languages like Java and PHP have made memory pointers much less important. For better or worse, programming has become a much less daunting endeavour now.
- number (integer, float)
var a = 'string'; var b = 1; var c = b; b = a; console.log(a); //'string' console.log(b); //'string' because of b = a console.log(c); //retains 1
So a variable can be assigned one type (integer) and re-assigned to another (string) with no confusion.
In a straight-up assignment, you expect
b to be updated with the
What is not clear to beginners is since
c is assigned the
b, does changing the value of
b affect the value of
In a language with pointer arithmetic (such as C), things will be different, and a little complicated, when pointers come into the picture.
Things become interesting when you start working with contents of arrays.
Let’s see what happens if the value of the array is assigned to another variable.
var a = [1, 2]; var b = a; var c = a; b = 3; console.log(a); //shows [3, 2] console.log(b); //shows [3, 2] console.log(c); //shows 1, not 3
If you are expecting
c to show the value of 3, you are not alone.
What happens here is that when the assignment of
c happened, a
copy of the value in
b was made and assigned to
b was assigned
a, a copy of the location of the array in
memory was made and assigned to
b. Thus, when
referenced, they both point to the same location in memory i.e. the
In summary, the difference between the examples lies in the fact that with array values, we are essentially working with memory locations as compared to actual values.
I’m deferring the use of the terms “pass-by-reference” and “pass-by-value” here because, like politics, everyone has his/her own opinions, and everyone disagrees with everyone else’s views. Things become even more complicated when you are talking about a language that does not have direct memory arithmetic.