ยง2023-08-14

javascript Copy code const variableName = value; For example:

javascript Copy code const pi = 3.14159; const greeting = "Hello, world!"; Key points to remember about const:

Immutable Value: The value assigned to a const variable cannot be modified after the initial assignment. This means you cannot reassign a new value to a const variable once it has been declared.

Block Scope: Like let, const is block-scoped. It means the variable's scope is limited to the block (usually defined by curly braces {}) in which it is declared.

Hoisting: Like let, const is also hoisted to the top of its scope but is not initialized until the actual declaration.

Assignment During Declaration: When using const, you must assign a value to the variable during its declaration. Unlike let, you cannot declare a const variable without initializing it.

Object and Array Properties: While a const variable itself cannot be reassigned, it doesn't make the object or array it references immutable. You can modify the properties of objects or elements of arrays declared using const, but you can't reassign the entire object or array to a new value.

Here's an example showing how const works:

javascript Copy code const number = 42; console.log(number); // Output: 42

number = 99; // This will result in an error since you can't reassign a const variable javascript Copy code const person = { name: "Alice", age: 30 };

person.age = 31; // This is allowed, as you're modifying a property of the object person = { name: "Bob", age: 25 }; // This will result in an error In general, use const when you have a value that should remain constant throughout its scope. If you expect the value to change or be reassigned, then use let.

Regenerate