Search This Blog

2026/08/09

Javascript : Guess Output


Guess what the output of the following code will be:

let n=20
console.log(n + 1); // 21, n is still 20 (no change)
console.log(++n);   // 21, pre-increment: increment first, then print (n becomes 21)
console.log(n++);   // 21, post-increment: print first, then increment (n becomes 22)
console.log(n);     // 22, current value of n

Output:
21
21
21
22

Explanation:
1. `console.log(n + 1);` - This line adds 1 to n (which is 20) and prints the result (21).
The value of n remains unchanged.
2. `console.log(++n);` - This line increments n by 1 (making it 21) and then prints the result (21).
3. `console.log(n++);` - This line prints the current value of n (21) and then increments it by 1 (making it 22).
4. `console.log(n);` - This line prints the current value of n (22).


 

No comments:

Post a Comment