sakthi M
sakthi M

Reputation: 19

Can someone explain this code in JavaScript with ++ and brackets?

var m=10;
n=(m++)+(++m)+(m++)+(++m);

Output is

n=48 m=14

How does this answer occur?

Upvotes: 1

Views: 136

Answers (2)

Pirate
Pirate

Reputation: 1185

Initially m=10. Now when ++ is executed, it will add 1 to the variable. In your code, there are 4 occurences of either ++m or m++, so it will be 14 at the end.

When ++ appears before the variable like ++m, it will add 1 first and use the variable in code. But when it appears after the variable like m++, the variable will be used first and then add 1.

So in n=(m++)+(++m)+(m++)+(++m);,
m++ - m will be used in code as 10 and becomes 11.
++m - m will be incremented by 1 first, so 11+1 =12 and will be used in code.
m++ - m will be used in code as 12 and becomes 13.
++m - m will be incremented by 1 first, so 13+1 =14 and will be used in code.

So, final result will look like this: n=10+12+12+14

var m = 10;
var m1 = m++;
var m2 = ++m;
var m3 = m++;
var m4 = ++m;
var n = m1 + m2 + m3 + m4;
console.log('n: ' + n);
console.log('m: ' + m);
console.log('(m++): ' + m1 + ', (++m): ' + m2 + ', (m++): ' + m3 + ', (++m): ' + m4);

console.log('---');
var x = 10;
var y = (x++) + (++x) + (x++) + (++x);
console.log('y: ' + y);
console.log('x: ' + x);

Upvotes: 6

Pooja Kushwah
Pooja Kushwah

Reputation: 187

m++ this will use previous value of m then increment. ++m this will first increment and then use the incremented value of m.

now, n=(m++)+(++m)+(m++)+(++m);

-> m++ here the value of m will be first used then increased by 1. so expression will be 10 + (++m) + (m++) + (++m). and for further value of m will be 11.

-> for next it is ++m so it will first increment then use in expression. so previously the value of m was 11, now 11+1 is 12. so expression will look like 10+12 + (m++) + (++m).

-> similarly to first point here also it will first used then increment. so expression will be n=10+12+12+(++m). but after this the value of m is now 13.

-> so here (++m) it will first increment and then add. so previously the value was 13 so 13+1=14. so m is 14 and expression will be n=10+12+12+14.

so the value of n=48 and m=14

Upvotes: 0

Related Questions