Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript variable initialization

Tags:

javascript

php

There, an odd thing just happened..

Normally I assign my global variables like this:

orders = [];
pOrders = [];

But I was lazy and just wrote:

orders = pOrders = [];

It should mean the same, shouldn't it??

Apparently not because the array pOrder also contained the array orders data. I sat for 15 min looking for a bug in my code but couldn't find any so I just tried writing the variables as I normally would and it worked. Why does this happen?

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

Please could anyone provide me with some information, or knowledge..

like image 538
Jacques Avatar asked Dec 07 '22 05:12

Jacques


1 Answers

In the second example, you're explicitly assigning the exact same array instance to two separate variables. There's only one array involved, while in the first case there are two.

I would be somewhat surprised to learn that PHP really would treat those two pieces of code as meaning the same thing.

like image 120
Pointy Avatar answered Dec 24 '22 13:12

Pointy