Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are elements of Javascript arrays processed in a defined order?

Tags:

javascript

For example:

var a = [];
function p(x) { a.push(x); }

[[p(1),p(2)],p(3),[p(4),[p(5)]],p(6)]

a == [1,2,3,4,5,6] // Always true?

Is 'a == [1,2,3,4,5,6]' defined behavior? Can it be relied upon?

like image 209
Samuel Danielson Avatar asked Feb 24 '23 16:02

Samuel Danielson


2 Answers

Are elements of Javascript arrays processed in a defined order?

Yes they are.

Is 'a == [1,2,3,4,5,6]' defined behavior? Can it be relied upon?

No, the equals operator performs referential equality when comparing object.

like image 175
ChaosPandion Avatar answered Feb 27 '23 05:02

ChaosPandion


Short answer: "Yes".

Longer answer: Your question is actually about JavaScript statements in general and not Arrays. The code you posted ([[p(1),p(2)],p(3),[p(4),[p(5)]],p(6)]) is not an Array, it is a statement that returns an Array whilst also populating an Array. JavaScript statements are executed according to the rules of operator precedence.

like image 28
gilly3 Avatar answered Feb 27 '23 04:02

gilly3