Course
Constants
JavaScript Tutorial
This JavaScript tutorial is crafted for beginners to introduce them to the basics and advanced concepts of JavaScript. By the end of this guide, you'll reach a proficiency level that sets the stage for further growth. Aimed at empowering you to progress towards becoming a world-class software developer, this tutorial paves the way for a successful career in web development and beyond.
Constants
JavaScript Constants
In JavaScript, a
constant
is a variable that cannot be reassigned or redeclared once it has been initialized. This means that the value of a constant remains fixed throughout the program.
To declare a constant in JavaScript, you use the
const
keyword followed by the name of the constant and its initial value. For example:const x = 10; // Correct Way
In any case, you can't declare the variables with the const keyword without initialization.
const y; // Incorrect wayy = 20;
Can't be Reassigned
You can't update the value of the variables declared with the const keyword.
const y = 20; y = 40; // This is not possible
Block Scope
A JavaScript variable declared with const keyword has block-scope. This means same variable is treated as different outside the blcok.
In the below example, the x declared within block is different from x declared outside the blcok. So we can redeclare the same variable outsite the block
{const x = "john";}const x = "Doe"
But we can't redeclare the const varaible within the same block.
{const x = "john";const x = "Doe" // incorrect}