What is a variable?

All computer languages are dealing with data. A variable is a box that can hold data. The data have a specific type: Number, Character, String, Date, Time, or a complex object like image or collection of numbers.

Declaring a variable

Let’s take a look at the syntax for creating a variable in JavaScript. To create a variable we use the keyword var and then write the name we’re giving to the variable. For instance, let’s create a variable called salary:

var salary;

In this case the salary will have a default value: undefined

Later we need to assign a value to a variable to be useful.


Assign a value to your variable

A JavaScript variable can be of different data types. It can be numeric, string, or boolean data type. To make the variable “salary” be of a numeric data type, we will simply assign a number after variable creation using “=” operator.

//Declare an integer variable using type inference
salary = 1000;

//Alternatively, we can assign the variable a string value:
salary = "entry level";

//We can also assign it a boolean value:


//We can also declare and assign a variable 
//on the same line in order to make our code shorter:

var salary = 1000;

//Later in our code, we might decide we want to change 
//the value of our variable. To do that, 
//we simply assign our variable a new value:

var salary = 2000;


Note:By changing the value of a variable we can also change the type of the variable. We can also re-declare a variable in JavaScript. In this case the old value of the variable is preserved until we assign a new value.


Declare many variables

We can declare more than one variable into a single line.

//declare 3 variables on single line
var driver = "John", car = "Acura", year = "1999";

//declare 3 variables in one single statement
  driver = "Xena", 
  car = "Porche", 
  year = "2015";