Menu Close

Articles

JavaScript: variable

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.

 

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.