0

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!

3 Answers 3

2
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.

Sign up to request clarification or add additional context in comments.

3 Comments

It may be worth noting that ++num1 +3 would produce the result expected in the question.
@user2196989 Absolutely.
ok…that explains it. Thanks. I was adding the num1 value of 20 and 3 and then increasing that by 1 and getting 24. I guess num1++ is totally separate, kind of..?
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.