Back to subject
JavaScript/Data Types

See a Value's Real Type

Practical lesson

Let's use typeof to confirm exactly what each variable is holding, rather than assuming.

const text = "Ali"; holds a String, const num = 16; holds a Number, and const isStudent = true; holds a Boolean. Nothing about how they're written tells you their type at a glance except the quotes (text) versus no quotes (num, isStudent).

${typeof text} inside the template literal evaluates to the word "string" typeof always returns its answer as text, which is why it displays correctly inside the page.

Running this, you'll see three lines confirming each type explicitly: string: Ali, number: 16, boolean: true. This kind of explicit check is exactly what you'd do while debugging real code, when a value isn't behaving the way you expect and you want to confirm what it actually is before assuming why.

Try changing const num = 16; to const num = "16"; (with quotes) and re-running typeof would now report "string" instead of "number", even though it visually looks like a number. This is the exact kind of subtle bug typeof helps you catch.

Try it yourself
Code

Starter example

Code
<script>
  const text = "Ali";
  const num = 16;
  const isStudent = true;
  document.body.innerHTML = `
    <p>${typeof text}: ${text}</p>
    <p>${typeof num}: ${num}</p>
    <p>${typeof isStudent}: ${isStudent}</p>
  `;
</script>
Live preview