What is a Variable?

A JavaScript program needs to use values, and that is where variables come into play. A program stores data in variables and assigns a name to refer to them in your program. In this section, we'll look at how to "declare", "initialize", and "update" variables in JavaScript.

After reading this section, consider these questions: 

  • How would programs be written without variables?
  • What is the difference between "declaring" and "initializing" a variable?

What is a variable?

A variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence. Let's look at a simple example:

button id="button_A">Press me</button>
<h3 id="heading_A"></h3>
const buttonA = document.querySelector('#button_A');
const headingA = document.querySelector('#heading_A');
    
buttonA.onclick = function() {
   let name = prompt('What is your name?');
   alert('Hello ' + name + ', nice to see you!');
   headingA.textContent = 'Welcome ' + name;
}

In this example pressing the button runs some code. The first line pops a box up on the screen that asks the reader to enter their name, and then stores the value in a variable. The second line displays a welcome message that includes their name, taken from the variable value and the third line displays that name on the page.

To understand why this is so useful, let's think about how we'd write this example without using a variable. It would end up looking something like this:

<button id="button_B">Press me</button>
<h3 id="heading_B"></h3>
const buttonB = document.querySelector('#button_B');
const headingB = document.querySelector('#heading_B');
    
buttonB.onclick = function() {
   alert('Hello ' + prompt('What is your name?') + ', nice to see you!');
   headingB.textContent = 'Welcome ' + prompt('What is your name?');
}

You may not fully understand the syntax we are using (yet!), but you should be able to get the idea. If we didn't have variables available, we'd have to ask the reader for their name every time we needed to use it!

Variables just make sense, and as you learn more about JavaScript they will start to become second nature.

One special thing about variables is that they can contain just about anything – not just strings and numbers. Variables can also contain complex data and even entire functions to do amazing things. You'll learn more about this as you go along.

Note: We say variables contain values. This is an important distinction to make. Variables aren't the values themselves; they are containers for values. You can think of them being like little cardboard boxes that you can store things in.


Source: Mozilla, https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables#what_is_a_variable
Creative Commons License This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.