Use Constant in JavaScript

Use Constant in JavaScript

Instructor-svgAl-Mamun Sarkar
Mar 29 , 2021

We can use a constant in JavaScript programs using the const keyword. Constant is the same as variables but the difference is we can't change the value of constant. 

Example:

const name = "Jone Doe";
const a = 12;
const b = 45;
const c = b + a;

console.log(c);

 

We can't reassign value to a constant.  

name = "Jone Doe"; // This will raise error

 

const also used inside a scope similar to let.

var x = 10;
{
  const x = 2;
}
console.log(x); // Output will be 10;

 

We can create a const object. For objects, we can't change that but can change the value of the objects's property. 

const student = {
	name:"Jone", 
	roll:12, 
	gpa:3.56
};

// You can change a property:
// This will work properly
student.roll = 10;
student.gpa = 5.00;

// We can't do that 
// This will raise error
student = {
	foo: "Hello",
	bar: "Welcome" 
}

 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram