How do I use this JavaScript variable in HTML?

Solution 1:

You don't "use" JavaScript variables in HTML. HTML is not a programming language, it's a markup language, it just "describes" what the page should look like.

If you want to display a variable on the screen, this is done with JavaScript.

First, you need somewhere for it to write to:

<body>
    <p id="output"></p>
</body>

Then you need to update your JavaScript code to write to that <p> tag. Make sure you do so after the page is ready.

<script>
window.onload = function(){
    var name = prompt("What's your name?");
    var lengthOfName = name.length

    document.getElementById('output').innerHTML = lengthOfName;
};
</script>

window.onload = function() {
  var name = prompt("What's your name?");
  var lengthOfName = name.length

  document.getElementById('output').innerHTML = lengthOfName;
};
<p id="output"></p>

Solution 2:

You can create a <p> element:

<!DOCTYPE html>
<html>
  <script>
  var name = prompt("What's your name?");
  var lengthOfName = name.length
  p = document.createElement("p");
  p.innerHTML = "Your name is "+lengthOfName+" characters long.";
  document.body.appendChild(p);
  </script>
  <body>
  </body>
  </html>

Solution 3:

You can create an element with an id and then assign that length value to that element.

var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('message').innerHTML = lengthOfName;
<p id='message'></p>