Variable in JavaScript

Variable is used to store the value in the physical memory.
Whenever we create the variable some physical memory gets allocated to it.

Syntax of declaring the variable:

There are two ways of declaring the variable:

Declaring and defining the variable at the same time:

We can declare and give the value to the variable at the same line.

Example:-

var num1=10;
var strnum1='10';

Only declaring and defining in another line:

We can declare variable in one line and give the value to the variable at somewhere else in the programe but after declaration.

Example:-

//declaring
var num1;


//defining
num1=10;
//error
num1=10;


//declaring
var num1;

There are three types of keywords by which we can declare the variable:

var:-

variables declared with the var keyword are globally and function scoped.
variables are intialized by undefined if declaration is only done.Variables can re-declared.

Example:-

//declaring
var num1;
console.log(num1)//undefined

//defining
num1=10;

let:-

variables declared with the let keyword are the block scoped.
Variables can re-declared.

Example:-

//let keyword
let num1=9;

const:-

variables declared with the const keyword are block scoped.
Variables cannot be re-declared and redefined. Variables should defined at the time declaration.

Example:-

//declaring
const num1=12;

We don’t need to explicitly declare the type of the variable. Variable data type depends on the type of the value assigned to it. There are advantages and disadvantages of this feature of the JavaScript.

advantage:-

You don’t have to declare th many variables as it can hold any type of data at the run time.

disadvantage:-

Sometimes because of run time datatype assignment, it is difficult to find error cause and also it creates confusion.

note:-

To overcome from the demerit of the JS. Microsoft created on more language which is TypeScript. It is type safe language which runs on the top of the Javascript.