const is a javascript keyword used to declare variable, whose value is assigned during declaration and cannot be changed or modified through out the program. Its value can only be used to perform operations. const variable has block scope. It is introduced in ES16 (2015).

  1. const variable initialization is mandatory.
  2. const variable value cannot be reassigned.
  3. const variable cannot be redeclared.
  4. const variable has block scope.
  5. const variable can be declared in different scopes like block, function or Global.

Declaring variable with const

Syntax

const variable_name =  initializer;

Example

const variable with Global Scope

<script>
const PI = 3.14;
</script>

const variable with block Scope

<script>
{
const PI = 3.14;
}
</script>

Cannot Redeclaring a const variable

<script>
const PI = 3.14;
const PI = 3.14; // Error: cannot redeclare a const 
</script>

Variable once declared with const cannot be redeclared.

Cannot Reassigning a const variable

<script>
const PI = 3.14;
PI = 3.14; // Error: cannot reassign a const 
</script>

const variable is initialized once during declaration, and const variable cannot be reassigned or changed with new value.

Declaring const with function scope

<script>
function getPI()
{
        //function scope
	const PI = 3.14;
	document.write(PI); //  outputs 3.14
}
getPI();
document.write(PI); // Error, because PI has function scope
</script>

A const variable declared in function scope is only accessible inside function, accessing outside function gives error.

Declaring const with function and global scope

<script>
//Global scope
const maxSpeed = 180;
function getSpeed()
{
        //function scope
	const maxSpeed = 100;
	document.write(maxSpeed); //  outputs 100
}
getSpeed();
document.write(maxSpeed); // outputs 180
</script>

const variable maxSpeed is declared outside function and inside function getSpeed(), So, one which is declared outside function has global scope and one which is declared inside function has function scope.

Const declared with Global scope only

<script>
//Global scope
const maxSpeed = 180;

function getSpeed()
{
       	maxSpeed = 100; // Error: cannot reassign a const 
        // Script execution stops due to reassign a const
	document.write(maxSpeed); 

getSpeed();
document.write(maxSpeed); 
</script>

const variable maxSpeed is reassigned inside function, due to this, execution stops because of reassigning a const variable.