Javascript variable initialization

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..


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.

That code you wrote there last is the same as:

orders = [];
pOrders = orders;

So now you have two variables which are references to the same array. That's why you are exeriencing this behavior.

When instead you do it as you did in your first example:

orders = [];
pOrders = [];

Then you have two completely separate and distinct arrays.

You assigned both variables to refer to the same array instance.

To see what everyone means by "same array instance", run the following JavaScript in your browser:

orders = pOrders = [];

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

Need Your Help

Header width not 100% with CSS and Viewport

html css header width mybb

I've tried the Viewport meta tag to fix this bug but I'm not so sure why it's occuring. Here's a screenshot of the problem:

Mysql Order by changeable field

java mysql sql

I am trying to create a mysql select query, using a changeable order by field criteria.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.