Hey everyone,

I tried testing this code if it is true or not. But,apparently, it is indeed true. So, it is not like referencing an element in array and changing its value. Can someone explain it why this is exceptional with numbers, please?

var a = 3.14; // Declare and initialize a variable
var b = a; // Copy the variable's value to a new variable
a = 4; // Modify the value of the original variable
alert(b) // Displays 3.14; the copy has not changed

Why is this happening? and it is so different from the code below:

var a = [1,2,3]; // Initialize a variable to refer to an array
var b = a; // Copy that reference into a new variable
a[0] = 99; // Modify the array using the original reference
alert(b); // Display the changed array [99,2,3] using the new reference

Recommended Answers

All 2 Replies

At a guess, I would think it has to do with the data type.

In your first example, you're using simple variables, floats, ints, etc. In the second, you're using arrays, which in JavaScript are objects.

Therefore, when assigning a variable to var a, you're actually just passing it a reference in memory. When you set var b = a, you're setting it to point to the same reference in memory.

To truly duplicate the array, you'd need to clone it.
var b = a.slice(0);

I know what it is now. I've read about it and it is to do with primitive and object types.
Thanks for the comment.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.