Javascript variable initialization

A strange thing happened there.

I usually assign my global variables as follows:

orders = []; pOrders = []; 

But I was lazy and just wrote:

 orders = pOrders = []; 

That should mean the same thing, right?

Apparently not because the pOrder array also contained the data from the orders array. I sat for 15 minutes, looking for an error in my code, but could not find anything, so I just tried to write the variables, as I usually did, and it worked. Why is this happening?

In PHP, the logic will be the same, but JavaScript seems to behave differently.

Please someone can provide me some information or knowledge.

+4
source share
4 answers

In the second example, you explicitly assign the same array instance to two separate variables. There is only one array, while in the first case there are two.

I would be somewhat surprised to learn that PHP will really treat these two pieces of code as one and the same.

+7
source

This code you wrote there is the same as:

 orders = []; pOrders = orders; 

So now you have two variables that are references to the same array. That is why you are performing this behavior.

If you do this, as in the first example:

 orders = []; pOrders = []; 

Then you have two completely separate and different arrays.

+5
source

You have assigned both variables to refer to an array instance of the same .

+2
source

To find out that everything means โ€œthe same array instanceโ€, run the following JavaScript in your browser:

 orders = pOrders = []; orders.push("hello"); pOrders.push("world"); console.log(orders); console.log(pOrders); 

Check the console output, both messages will say ["hello," "peace"].

+1
source

Source: https://habr.com/ru/post/1498612/


All Articles