1

I am very new to Javascript and programming in general so I am trying to build a simple maths app to get some practice in. I am able to get the code to work as intended, but only if I don't put .textContent when defining my variables, and put them later on, however this is clunky and DRY. If I put them into my variables the html returns nothing in the empty spans (all IDs in the code are empty spans), so it's like the page loads and then it's not updating with the values calculated from Javascript? How can I capture what I'm after in the variable without having to add .textContent every time in the second part?

I have tried using .value instead of textContent. It's only if I add .textContent to the second part and leave it out of the first part that the numbers are generated and rendered on the page normally.

startNumber span is empty when page loads:

var startNumber = document.querySelector("#startNumber").textContent;
startNumber = Math.floor((Math.random() * 20) + 1);

startNumber span has random number between 1 and 20 when page loads:

var startNumber = document.querySelector("#startNumber");
startNumber.textContent = Math.floor((Math.random() * 20) + 1);

I expect both to work but only the second one does, which means I have to write .textContent every time I refer to the number in the span.

Community
  • 1
  • 1
mhavenhand
  • 11
  • 1
  • `document.querySelector("#startNumber").textContent` is just an ordinary string. The span can't be referenced from it. So in the first version, you're just assigning a string to the variable `startNumber` and then reassigning it (a `number`) on the next line. In the second version `startNumber` is the actual span element and you can set the content of it by assigning to `startNumber.textContent`. – Paul Jul 04 '19 at 18:00

1 Answers1

0

Only objects and array are references, strings are passed/copied as values.

document.querySelector("#startNumber") is an object, a reference. document.querySelector("#startNumber").textContent is an string, not a reference

see: Javascript by reference vs. by value

Puggan Se
  • 5,738
  • 2
  • 22
  • 48