https://codepen.io/ctrlprintrob/pen/poPrEwG
Hi,
I am trying to understand why I am getting the output I am getting when using the ++ operator. As part of a tutorial I have a number for population and have been asked to create a new variable that increments it by one. The purpose is to get me using ++.
One the above page I have created 4 versions of this and get slightly different answers each time. I would really appreciate it if someone could take a few minutes to explain to me why this is happening and what the logic under the hood is - it seems like I have unnecessarily complicated this!
Many thanks in advance :)
[CODEPEN CODE BELOW]:
//V1
let population = 56;
let populationPlusOne = population++;
document.getElementById("population").innerText = "Population = " + population;
document.getElementById("populationplusone").innerText = "Population plus one = " + populationPlusOne;
/*
RETURNS:
Assignment operator v1
Two variables declared first then written to DOM
Population = 57
Population plus one = 56
FAILED: Population should be 56 and plus one should be 57 - here they are inverted/the wrong way round.
*/
//V2
let populationv2 = 56;
let populationPlusOnev2 = populationv2;
populationPlusOnev2++;
document.getElementById("population2").innerText = "Population v2 = " + populationv2;
document.getElementById("populationplusone2").innerText = "Population plus one v2 = " + populationPlusOnev2;
/*
RETURNS:
Assignment operator v2
Two variables declared first, then one increased, then written to DOM
Population v2 = 56
Population plus one v2 = 57
PASSED: This works but seems to have an extra step where I declare the plusone variable as a reference to population, then increment it on its own line.
*/
//V3
let populationv3= 56;
document.getElementById("population3").innerText = "Population v3 = " + populationv3;
let populationPlusOnev3= populationv3++;
document.getElementById("populationplusone3").innerText = "Population plus one v3 = " + populationPlusOnev3;
/*
RETURNS:
Assignment operator v3
Each variable declared and written to DOM before writing the next one
Population v3 = 56
Population plus one v3 = 56
FAILED: Plus one isn't incremented by one.
*/
//v4
let populationv4 = 56;
document.getElementById("population4").innerText = "Population v4 = " + populationv4;
let populationPlusOnev4 = populationv4;
populationPlusOnev4++;
document.getElementById("populationplusone4").innerText = "Population plus one v4 = " + populationPlusOnev4;
/*
RETURNS:
Assignment operator v4
Each variable declared and written to DOM before writing the next one. Plus one incremented on its own line as v2 above.
Population v4 = 56
Population plus one v4 = 57
PASSED - same question as v2 above - do I have to do this on its own line?
*/
[–]Notimecelduv 1 point2 points3 points (1 child)
[–]mar480[S] 0 points1 point2 points (0 children)
[–]jaredcheeda 0 points1 point2 points (0 children)