What is a variable? In JavaScript

What is a variable? In JavaScript



The goal of a program is to do something with data, or in other words, stuff you put into your program. Your program uses variables to store and manipulate that data. More specifically, a variable is a container used to store a piece of the data that your program needs to work. A username, the number of available tickets left for a flight, whether or not a certain product is in stock — all of this data is stored in variables.


A piece of data placed in a variable is called a value. Using the "box-in-a-warehouse" analogy, different boxes can store different values. For example, you can use one box to store money for ongoing expenditures, and another to save up for a specific occasion, like going on a trip. You can also empty the boxes or change their content, like adding some money or taking some out.

To know what each box is for, you need to label them. With programming, it's the same: you assign a name to your variable. A variable's name should reflect the meaning of its contents like labels on boxes. Here are some general recommendations for creating names:

  • Use descriptive names throughout your code
    Did you ever fish an old folder out of a box labeled "admin stuff" on the cover? Remember how frustrating that was? Being descriptive and specific in variable names makes life far easier: it makes your code easier to read and to maintain. Instead of  amount (or even worse,  amt), add some detail:  quantityInStock,  currentBalance, etc.

  • Spell it out
    Avoid abbreviation or shortening words when possible; even if a shorter version seems obvious. For example, annualRevenue is better than annualRev.

  • Follow a common naming convention
    One of the popular naming conventions is called camel case — names made up of multiple words where all but the first are capitalized e.g. numberOfCats,  finalAnswer,  howLongCanThisVariableNameGet, etc.