Skip to main content
P.M.B
Legend
July 3, 2017
Question

Newbie Question

  • July 3, 2017
  • 1 reply
  • 362 views

Hi,

So even though this question doesn't pertain to Acrobat I'm asking it here because it's a javaScript question.

I have a little scripting experience but I'm brand new to JavaScript.

Can someone please explain the example of the ++ operator found on this page?

The example is below so you don't actually need to follow the link.

Arithmetic operators - JavaScript | MDN

// Postfix

var x = 3;

y = x++; // y = 3, x = 4

// Prefix

var a = 2;

b = ++a; // a = 3, b = 3

A little history...

I was trying to increment a variable by one through each iteration of a conditional statement.

I was trying to duplicate an item "x" number of times until "x" equaled 10.

I basically wrote the offending line of code as     x = x++;

That statement sent the script into an infinite loop.

I did this based on my experience with MEL for Maya.

So from what I read & what was explained to me about JavaScript

I learned that unlike the other language I know

a postfix ++ operator would keep the variable the same &

a prefix ++ operator would increment it by one.

However in the above example I am confused by two things:

first: the inclusion of the second variable "b"

second:  In both the postfix & prefix examples "x" gets incremented by one

If postfix is supposed keep the value the same & prefix is supposed to add 1, then why do both examples add 1?

For bonus points & if it's not too much trouble....

Pertaining the postfix operator keeping the same value....

Why might I want to add an operator to a variable that does nothing? (keeps it the same)

Thanks for taking the time to read this & I appreciate any help.

This topic has been closed for replies.

1 reply

try67
Community Expert
Community Expert
July 3, 2017

The prefix-version executes before the rest of the code in that line. The

postfix-version executes after it.