src091
src091

Reputation: 2847

Calling a function with incremented values

If I call a function like this:

var n = 0; f(n, n += 100)

the values of it's arguments are 0 and 100, not 100 and 100 as I would have expected. This behavior does what I currently need in my program but I don't understand why it works this way and it troubles me.

Can someone explain why it happens so and whether it's safe to pass arguments like this?

Upvotes: 0

Views: 766

Answers (3)

Daniel Brockman
Daniel Brockman

Reputation: 19270

Unlike C (and like Java), Javascript does in fact have a defined order of argument evaluation: left-to-right. So, somewhat surprisingly, it is safe to write the code as you have. However, I would consider it very poor style and in fact almost unreadable since not many people know off the top of their heads whether the evaluation order is in fact defined (case in point: I had to look it up to answer this question).

Edit: See section 11.2.4 http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

Upvotes: 2

Chris Shouts
Chris Shouts

Reputation: 5427

The variable n is a primitive type in JavaScript (the primitive types include numbers, string, and boolean values). Primitive types are passed by value, explaining the behavior you observed. If n were a non-primitive type, it would be passed by reference and any modifications made to it would be reflected in all references to n.

See JavaScript: Passing by Value or by Reference for additional information.

Upvotes: 1

SLaks
SLaks

Reputation: 887385

The first parameter value is evaluated before the second one.

Upvotes: 4

Related Questions