JavaScript variables

What are variables in JavaScript?

A variable is fundamental for any language. Like C, C++ and other programming language JavaScript also allow you to declare variables. A variable is nothing but a storage which holds your data. It can be simply compared with containers in your house’s kitchen which are used to store different items. Some containers are used to store cereals, some are used to store edible oil and so on.

Variables in JavaScript also stores items in the same way as containers store. A variable is capable to store data in the form of numbers, characters, strings, boolean values etc. The data or value stored in the variables can be set, updated, and retrieved whenever needed. In general, variables are symbolic names for values.

You can create a variable with the var keyword, whereas the assignment operator (=) is used to assign value to a variable, like this: 

var varName = value;

The syntax of variable declaration is shown below.

var firstName="Rakesh";
var firstNumber=5;
var isMarried=false  //boolean

As you know JavaScript is case-sensitive, you cannot use the variable FirstName in place of firstName. Always give meaningful name to your variables to avoid confusion in future. If a long variable has been declared then it is good practice to use camelCase. In our example above, first variable is string, second variable is number and the third variable is boolean.

In JavaScript, variables can also be declared without having any initial values assigned to them. This is useful for variables which are supposed to hold values like user inputs. Example is given below:

var firstName;

firstName="Rajan";

Note: If a variable is declared and the value has not been assigned to it, then the variable will automatically assume undefined.

Declaring Multiple variables in JavaScript

You can declare multiple variables in one line. The variables declared in one line will be separated by comma. The example of declaring multiple variables is shown below:

var firstName="Rakesh", firstNumber=5, isMarried=true;

Let and Const keywords in JavaScript

The let and const keywords are also used to declare variables. The const keyword works same as let except for one change. The variable declared as const cannot be reassigned later but the variable declared as let can be reassigned later.

// Declaring variables
let name = "Ramesh";
let age = 11;

// Declaring constant
const PI = 3.14;
// Trying to reassign
PI =52; // error