Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between p++ and ++p when using that in a for loop Javascript

This could be a very naive dumb question, but what is the difference in the output of the following 2 condition:

for (var p=0; p<3; p++) {console.log(p)}
//outputs:
0
1
2


for (var p=0; p<3; ++p) {console.log(p)}
//outputs:
0
1
2

'p' result into same output regardless whether I increment the value first and then print it or vice vera. also I do understand the diff between (p++) and (++p), but in this case I'm unable to understand whether at this point in looping will it make it any difference if I were I do either of 2 or if it does make difference how would that impact my program.

Can someone please explain.

Thank

like image 706
user1234 Avatar asked Dec 17 '22 17:12

user1234


2 Answers

If you dont use the values, after using pre- and post-fix, there is absolutely no difference at all. (exept from performance)

Doing something like this would behave differently, as you can see:

var a = 0;
var b = 0;
var arr = [0,1,2];

console.log(arr[++b]);
console.log(arr[b++]);
console.log(arr[b]);
like image 168
DigitalJedi Avatar answered Feb 01 '23 23:02

DigitalJedi


In this case there is no difference whatsoever as you are not using the value of the expression.

like image 27
0x76 Avatar answered Feb 02 '23 00:02

0x76