What's the Logic Here, Please?


#1

Hi,

Can anyone tell me why the simple code below:

for (var x = 0; x < 26; x++) {
    document.write(x + ", " + (x++));
    document.write("<br>");
    document.write("<br>");
}

Outputs “0, 0”, “2, 2”, “4, 4” and so forth when I was expecting “0, 1”, “2, 3”, “4, 5” and so on??

Thanks!


#2

The code is incrementing x twice per iteration.

Change x++ to x += 2 in the loop parameter.

Also note that postfix doesn’t increment until after the statement. Prefix will do what you want.

x + ", " + (++x)

Now I think of it, don’t change the increment in the loop params.


Aside

That’s very old JavaScript from the HTML 4 days. That method hasn’t been used in more than a decade, ever since unobtrusive coding practices became the standard. Inline script is definitely frowned upon. Use the DOM and the given tools for this purpose.

let pageNode = document.querySelector('#page-node');

Now in the HTML,

<div id="page-node"></div>

That node will be cached and can be dynamically updated on the fly.

Now the loop can look like this… (kinda sortof)

for (let x = 0; x < 26; x++) {
    pageNode.textContent += `${x}, ${++x}`;
}
index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>incremented pairs</title>
    <link rel="author" href="https://repl.it/@mtf/Incremented-Pairs-DOM-demo">
    <link href="index.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div id="page-node"></div>
    <script src="index.js"></script>
  </body>
</html>
index.js
let pageNode = document.querySelector('#page-node');
for (let x = 0; x < 16; x++) {
  let paragraph = document.createElement('p');
  paragraph.textContent += `${x}, ${++x}`;
  pageNode.appendChild(paragraph)
}
Output
0, 1

2, 3

4, 5

6, 7

8, 9

10, 11

12, 13

14, 15

#3

Wait, what – why??

I read the code

for (var x = 0; x < 26; x++) {
    document.write(x + ", " + (x++));
    document.write("<br>");
    document.write("<br>");
}

Simple as:

  1. create variable x
  2. set x to zero
  3. as long as x is less than 26, perform Step 4
  4. display the value of x, then display the value of x increased by 1
  5. increase x by one

Why’s JavaScript going out of turn to increase x before the loop’s done running??

And it doesn’t make sense that JavaScript increments x upon the first instance of x++ (the second line of code)

document.write(x + ", " + (x++));

but doesn’t increment x as per the final expression in the loop statement (the first line of code)

for (var x = 0; x < 26; x++) {

I find that my main problem is “getting” JavaScript’s “mindset”…I know that in at least this one instance

var myHouse1 = {color: "blue"};
var myHouse2 = myHouse1;
myHouse2.color = "red";
document.write(myHouse1.color + ", " + myHouse2.color);   // displays "red, red" (without quotes)

it’s due to the computer science matter of memory addresses – myHouse1 and myHouse2 are both “pointing to” the same memory address (which houses “red”), and that’s why one separate variable can have an effect on another separate variable, 'cause of weird under-the-hood stuff…but what’s happening here, please?


#4

Thanks a bunch!! That does the trick – I didn’t even know about that prefix thinggy!!


#5

Heck, from Javascript 1.1 – back when the name (its own) wasn’t camelCased; I remember!! I’d actually did the HTML for a college department back in HTML 2.0 days…bought the popular “Teach Yourself…in 21 Days” book by Laura Somebody and spent five weeks hacking away at the digital marble…but I didn’t realize the web was a thing back then and besides I didn’t want to spend my life in front of a CRT monitor (yes, funny how life works out, worse than a programming bug!!)…

Anyway, I’d googled this matter and I still don’t really get what the big deal is – I’m not using it in a real program, after all; just quickly typing stuff into online JS Code Editors to see what works and what doesn’t…I also didn’t understand all that stuff you’d mentioned about page nodes and whatnot; it’s all very above my ken right now – but I deeply appreciate your time and thoughts and will keep researching and try integrating the insight into my “personal knowledge base.”


#6

When we assign a reference to a variable, the variable always references that reference (arrays and objects are pointers). Change a value in either object and it will be changed on both.

Copying objects can be tricky, so do some reading on this to find out more about the subject. We can make a shallow copy using object.assign(), but this will not work on deep copying.

We can use a constructor to create two objects with a shared prototype, but which are independent of each other.

function Foo(name, color) {
    this.name = name,
    this.color = color
}

myHouse1 = new Foo('East-side', 'blue');
myHouse2 = new Foo('West-side', 'red');

console.log(myHouse1.color)    // blue
console.log(myHouse2.color)    // red

myHouse2.color = 'teal';

console.log(myHouse1.color)    // blue
console.log(myHouse2.color)    // teal

#7

That’s the thing to know – and keep in mind! – since at first glance, it looks like a value is being assigned (which is how beginners are taught [introduced to] variables), not that something is being referenced. I’m still having a bit of a hard time remembering this 'cause the underlying concept of a reference is a bit hazy…

It’s very interesting that the study of computer programming implicates human cognition – indeed, that’s a main attraction for me, as if programming was holding up a mirror (however fogged and cracked in my case!) to my own neural mechanics…

Amazing! Seems like such a fundamental use-case, the need to copy objects (especially in OOP!), that I’m surprised this is such a tricky matter!

And now I’ve got to “do some more reading,” as you advise – way over my head! ('Member, I only just found out about prefix-increments thanks to you!)


#8

When you get the unit(s) on objects the concept of custom object constructors will be covered. In the old days we would refer to these as classes, though in pseudo form, only. Modern ES has classes molded into the fray, but doesn’t escape the fact that JS/ES is prototypal, and not class based.

I would suspect that classes can be somewhat pre-compiled which helps to give the language more horsepower and efficiency, but that’s just a guess (even after all these years of tinkering still very much beginner oriented).


#9

Indeed…thanks again for the heads-up! Sorry I’ve no intelligible reply to make, really. :o)


#10

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.