Variable in Javascript

Javascript – Variable

A variable, as the name says is a name given to a memory location where different values can be stored and is associated with a symbolic name. Javascript is no exception and variables are expressed by ‘var’ keyword followed by its symbolic name.

var a = 3;
var b = 4;
var mul = a*b;

In the above example a,b and mul are the symbolic names given to values and thus they store the assigned values as well. As we see, its like maths, we can add,substract and do other operations on numbers stored in these variables.

But wait, can we only store number? No. A variable can have any value weather a number or a letter or a word(string).

var name = "Some Name"; or var name = 'Some Name';
var number = "4"; or var number = '4';

In the above examples, these string are enclosed in single quote(‘) or double quotes(“) but they work the same.

Ever thought how will you add a quotation mark because as soon as you add a quote the string will terminate.

JavaScript Identifiers

Identifiers are the unique names given to the variables and it should solve the purpose for variable declaration.

var x = 2;
var y = 4;
var z = 6;
var m = x*y*z;

Bad Identifier names

var length = 2;
var breadth = 4;
var height = 6;
var volume = length*breadth*height;

Proper Identifier names

Proper naming convensions

  • Variable must have a proper name and start with alphabet or _ symbol.
  • Variables are case sensitive
  • Reserved keywords cannot be used as a variable name.
  • Camel case should be used to join longer variables.

Decrating a variables and its Re-declaration

Instead on declaring a varible and initializing it with some value, we can simply do this without initialization. So now, this variable holds no value. But it is prefered to always initialize variable with some intial values.

var name;
name = "Some Name";

Multiple Declations

Multiple variables can be declared in the same line seperated by a comma.

var a = 9,b = 5 ,c = 3;
var a = 9,
b = 5,
c = 3;


Since variables are capable of solving complex problems, we can simple put any mathematical equation and its output will be stored in the variable.

var complexOperation = 3*4/3*(2^3+2)-5/3;

Similarly, string can also be concatinated in the variable

var fullName = "FName "+"LName";

Any idea what you will get if you combine a string with a number?? Well, try it yourself in your browser’s console.

Translate ยป