+ 3

What is the answer and why ? (JavaScript/Increments)

What will be alerted? n = 2; m = (n++ * 12); alert(m); Sololearn says the answer is 24. How is this? Why is it not 36?

26th Oct 2019, 12:17 PM
Zone
Zone - avatar
11 ответов
+ 15
The answer is 24, because n++ is a postfix increment. For instance if: n = 2 m = n++ ans: m = 2, n = 3. m is assigned the value of n before n is incremented. But in prefix increment: n = 2 m = ++n ans: m = 3, n = 3. n is incremented first and then assigned to m.
26th Oct 2019, 1:48 PM
Meny Evolving
Meny Evolving - avatar
+ 13
No Zone because the question says: m = (n++ *12); alert(m); At end of the code n is still 3 as there is no operation on it after incrementing.
3rd Nov 2019, 7:43 AM
Meny Evolving
Meny Evolving - avatar
+ 9
Zone happy to help
27th Oct 2019, 11:31 AM
Meny Evolving
Meny Evolving - avatar
+ 4
you are using a Postfix increment entry where the value of the variable changes by one after it is used in the alert output expression
26th Oct 2019, 12:47 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 2
it depends what you want to use it for. if the variable does not need to be output immediately, there will be no difference for you. any option will do. try to practice in different ways such as in a cycle and feel the difference. you can find an article in Google on this issue and delve, but for a clear understanding it is better to try it yourself. Just remember that in a Postfix notation, the expression first uses the old value and then increments or decrements it by one
26th Oct 2019, 1:10 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 2
36 you will receive in this case: if you do not use the increment in the next line ... alert(m); //end of your code 24 m = (n*12); alert(m); //36 becouse n was +1
26th Oct 2019, 1:30 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 2
check out these points in the codes section { }
26th Oct 2019, 1:31 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 2
Meny Evolving shouldn't the answer be 36 then since you said n = 3 ?
3rd Nov 2019, 12:38 AM
Zone
Zone - avatar
+ 1
You can put this code in code section { } and show us here?
26th Oct 2019, 12:45 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 1
Calviղ that was a typo on my end. I meant to type 24.
26th Oct 2019, 12:52 PM
Zone
Zone - avatar
0
Ярослав Вернигора (Yaroslav Vernigora) so are you saying i shouldn't be using postfix increment entry?
26th Oct 2019, 12:59 PM
Zone
Zone - avatar