Why a is equal to 11 & b is equal to 10? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why a is equal to 11 & b is equal to 10?

Hello, I'm completely new to JavaScript. Recently I was studying increment operators. And I'm unable to understand why the following code's variable named "a" is equal to 10! Please help me to understand this.. //Code// var a; var b; a = 10; b = a++; console.log("a = " + a); console.log("b = " + b);

19th Aug 2020, 4:58 PM
Abir Sheikh
Abir Sheikh - avatar
3 Answers
+ 3
Thanks for a nice question. For increment operator study your need to focus what is returned. That can solve your problem. It is the value of your variable which holds the increment operator. x++: If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing. Postfix increment: let x = 3; y = x++; // y = 3; returns the value before incrementing // x = 4; the increment operator increments ++x: If used prefix, with the operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing. Prefix increment let a = 2; b = ++a; // a = 3; the increment operator increments // b = 3; returns the value after incrementing Your Problem: Hope you realize that why your b has remained 10 and a is incremented..
19th Aug 2020, 5:08 PM
Bits!
+ 3
Hi I am steve, There is a post incrementing in setting var b. which will assign a and than add 1 to it. It would work if //Code// var a; var b; a = 10; b = ++a; console.log("a = " + a); console.log("b = " + b);
19th Aug 2020, 5:01 PM
Steve Sajeev
Steve Sajeev - avatar
+ 2
Abir Sheikh lets see your code a = 10 ; b =a++; Lets see var b. b = a++; means here increment operator is used but it is post increment so the value of a =10 will assign to b. So the value of b = 10. return to var a, is post increment so the value of a is increase by 1. So. The value of a = 11. I hope you understand
19th Aug 2020, 5:08 PM
Himanshu Shah
Himanshu Shah - avatar