Declaring (Creating) JavaScript Variables

Creating a variable in JavaScript is called "declaring" a variable. You declare a JavaScript variable with the var keyword:  var carName;

After this declaration, the variable has no value. (Technically it has the value of undefined.) To assign a value to the variable, use the equal sign:  carName = "Volvo";

You can also assign a value to the variable when you declare it:  var carName = "Volvo";

In the example below, we create a variable called carName and assign the value "Volvo" to it. Then we "output" the value inside an HTML paragraph with id="demo":

HTML file: Displayed by browser:
<body>
<h1>JavaScript Variables</h1>
<p>Create a variable, assign a value to it, and display it:</p>
<p id="demo"></p>
<script>
   var carName = "Volvo";
   document.getElementById("demo").innerHTML = carName;
</script>
</body>

JavaScript Variables

Create a variable, assign a value to it, and display it:


Good habit It's a good programming practice to declare all variables at the beginning of a script.
Back Table of Contents Next