Javascript variable and their scope

What is variable?

A Variable is a place holder/container for storing data.

The general rule of declaring variables:

  1. must be identified with unique names.

  2. can contain letters, digits, underscores, and dollar signs.

  3. must begin with a letter, can also begin with $ and _

  4. case sensitive (a and A are different variables).

  5. Reserved words (like JavaScript keywords) cannot be used as names.

There are 3 ways of declaring variables:

1. Using var:

Introduced in 1995 makes it suitable to run in older browsers.

If we need to store data that can be changed var is suitable.

Redeclaring won't change the value.

it doesn't have a block scope and declaring inside a block can be used outside also.

var carName = "Ciaz";
var carName ; //Redeclaring wont change the value
console.log(carName);

O/P: Ciaz

//Inside a block the value can be used outside.
{

    var a =10;
}
console.log(a);// output is 10

var $$$ = 2; //$ can be used
console.log($$$);

var _a = 2; // underscore can be used
console.log(_a);

2. Using let:

Introduced in ES6, it has a block scope and its value can be reassigned but can't be redeclared.

//block scope
{

    let a =10;
}
console.log(a);
O/P: ReferenceError: a is not defined

//Cannot be redclared
let a =10;
let a=12 ;
console.log(a);
O/P:Identifier 'a' has already been declared

//Can be reassigned
let a =10;
a=12 ;
console.log(a);
O/P: 12

2. Using const:

Introduced in ES6, it has a block scope and it cannot be redeclared and reassigned.

//block scope
{

    const a =10;
}
console.log(a);
O/P: ReferenceError: a is not defined

//Cannot be redclared
const a =10;
const a=12 ;
console.log(a);
O/P:Identifier 'a' has already been declared

//Cannot be reassigned
const a =10;
a=12 ;
console.log(a);
O/P: Assignment to constant variable.