Question

I am just learning Javascript and I don't understand why the below equation equals 23. I would say it should be 24.

In my online class, the explanation for why the answer is 23 is as follows:

"num1 is added to 3 and then incremented by 1(20+3)" This answer makes no sense to me.

var num1=20;
num2=num1++ +3;
alert (num2)

Any help would be appreciated!

Was it helpful?

Solution

var num1=20;
num2=num1++ +3;

What this says is: add 3 to the value of num1 and assign the result to num2. Then increment num1. After the operation is complete num1 == 21 and num2 == 23.

The result is 23, as you have found.

It's this sort of confusion that has led to pre- and post-fix operators being discouraged.

OTHER TIPS

Basically, the way the postfix ++ (specificially ++ AFTER a variable) is like a special function. It performs 2 actions

  1. Adds one to the variable
  2. Returns the variables original value

Compare this to a prefix operator, ++num1, which performs these 2 actions:

  1. Adds one to the variable
  2. Returns the new value

If it helps to see this in code, you could think of it as

function PlusPlus(num)
{
    var oldValue = num;
    num = num + 1;
    return oldValue;
}

Although this wouldn't actually perform the way you want it to because of pass by value, but that's besides the point. It can be tricky to remember the difference between prefix and postfix, but the main thing to remember is postfix comes AFTER the variable, and changes it AFTER everything else is done in the line, while prefix comes BEFORE the variable, and changes it BEFORE anything else is done.

The postfix increment in that basically does this:

var num2 = num1 + 3;
num1 = num1 + 1;

Equivalent code would be this:

var num1 = 20;
var num2 = num1 + 3; // 20 + 3 = 23
num1 = num1 + 1; // 20 + 1 = 21
alert(num2); // alerts 23

And the prefix increment operator (I know that this wasn't asked, but it may be useful) works like this:

/* Original code */
var num1 = 20;
var num2 = ++num1 + 3;
alert(num2);

/* Broken down code */
var num1 = 20;
num1 = num1 + 1; // 20 + 1 = 21
var num2 = num1 + 3; // 21 + 3 = 24
alert(num2) // alerts 24

Go ahead and ask if you have any more questions. I'll happily answer them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top