Javascript const
Created By: chatGPT
const
is a keyword in JavaScript used to declare a variable that cannot be reassigned. This means that once a variable is created with const
, you cannot change its reference to another object or value. However, if it's an object or an array, you can still modify its contents.const myConstant = 10;
myConstant = 20; // This will throw an error
You can create a
const
array or object, and while you can't reassign the variable itself, you can update the contents.const myArray = [1, 2, 3];
myArray.push(4); // Allowed, modifies the contents
const myObject = { key: 'value' };
myObject.key = 'new value'; // Allowed, modifies the property
Scope is another important aspect of
const
. The variable declared with const
is block-scoped, which means it exists only within the block where it is defined.if (true) {
const blockScopedVar = 'I am inside a block';
}
console.log(blockScopedVar); // This will throw an error
To summarize,
const
is used to create variables that should not be reassigned, and it works well with arrays and objects for manipulation of their contents. It is always a good practice to use const
for variables that you do not plan to change.const url = 'https://myapi.com'; // Good practice
// Example of error:
const myList = [];
myList = [1, 2, 3]; // Error