Different use of JavaScript ++ operator

I think the teacher of JavaScript Algorithm and Data Structure should be accommodative in approach . How is this incorrect?:
var myVar = 87;

// Only change code below this line

myVar = ++myVar;

I have written many for loop JavaScript codes as follows:
for (var i = 0; i < n; i++;)
I am confused as to what is required. Am I missing something?

Can you please post the link to the challenge?

I suspect that your issue is that the challenge wants you to only increment,
instead of increment and assignment (which is unnecessary)
myVar = myVar++

You can use the prefix or postfix increment, but you have to get rid of the assignment.

// or

The ++ before a variable and ++ after the variable makes a difference “when” the variable gets incremented.

++myVar //This is called pre increment
It means the variable gets increment first before you use it.

myVar++ //This is called post-increment
It means the variable gets increment AFTER the variable was used.

In your case in the for loop. i++ would mean that the variable i only gets incremented after the loop have successfully executed.

Pre-increment is rarely used

In a for loop, the increment variable update always occurs at the same time every iteration. Pre increment and post increment in the head of the loop produces the same results. You can change how the increment variable is updated but not when.

for (let i = 0; i < lim; i++) {

is the same as

for (let i = 0; i < lim; ++i) {

In the past, for equivalent C/C++ code, there used to be a minor performance difference between the two, but with modern compilers the performance is the same.

Hi, I have taken all suggestions on board. Still not working out. My earlier answer was ++myVar. This was accepted, but it insists on “This should be changed: myVar = myVar + 1;” . I changed this and replaced it with this: ++myVar (my earlier answer). It still insists that this, myVar + 1, be changed. But this is what I replaced and is no longer there.

You want to be using only the incrementor (++) without assignment (=).

Its saying that you should not use

myVar = myVar++

but instead


Thank you Jeremy. You are correct. It works out that way. I had figured it out and moved on. Sorry for my late response.

1 Like