자바스크립트 상수(Constant)

자바스크립트 상수(Constant)


When programming in JavaScript, you often come across situations where you need to use a fixed value that shouldn't change throughout the program. These fixed values are called constants. In JavaScript, you can declare constants using the `const` keyword.

```javascript
const PI = 3.14159;

console.log(PI); // Output: 3.14159

In the example above, we declared a constant named PI and assigned it the value of 3.14159. The value of PI cannot be changed later in the program.

Constants are useful when you have values that should remain constant and not be modified accidentally. By using constants, you can make your code more readable and maintainable. It also helps prevent bugs that can occur due to accidental changes to important values.

It is important to note that constants are block-scoped and cannot be redeclared or reassigned. Attempting to reassign a constant or declare a new constant with the same name will result in an error.

const PI = 3.14159;
PI = 3.14; // Error: Assignment to constant variable

const PI = 3.14; // Error: Identifier 'PI' has already been declared

Constants can be used in various scenarios, such as mathematical calculations, configuration settings, or any value that should remain constant throughout the execution of your program.

In conclusion, using constants in JavaScript helps you define fixed values that cannot be changed during program execution. They improve code readability, maintainability, and help prevent accidental modifications.