HTML chapters

Chapter 4 of 17

Variables

Try this in our HTML Compiler →

What is a variable?

A variable is a labelled box in the computer's memory. You put a value in the box, give the box a name, and later refer to the value by its name. Variables let you store user input, intermediate results and program state without hard-coding numbers and strings everywhere.

Declaring a variable

In HTML you declare a variable with the syntax shown below. Choose names that describe what the value represents: userAge is far better than x. Stick to one naming style across a project (camelCase, snake_case…) so the code stays consistent.

<!-- HTML does not have variables in the programming sense.
     Instead, you use elements and attributes to mark up content. -->
<p data-author="Aman">Welcome to my site</p>

Reassignment and scope

Most variables can be reassigned later — the box stays, the contents change. The places in your code where a variable is visible is called its scope. Variables declared inside a function are usually only visible inside that function, which keeps programs predictable as they grow.

Try it yourself

HTML Compiler
CSS (optional)
Output
Code runs in a sandboxed preview inside your browser — your code is saved locally for next time.